Canvas Learning: Drawing Rectangles

Pass the previous tutorial Learning, we can easily in Canvas Draw path (line segment) This is the case. This is just a small part of Canvas. Today we'll see how to draw rectangles in Canvas.

Method of Drawing Rectangles

API s for drawing rectangles are provided in Canvas:

  • fillRect(x, y, width, height): Draws a filled rectangle
  • strokeRect(x, y, width, height): Draws a rectangular border
  • clearRect(x, y, width, height): Clear the specified rectangular area to make the clearance completely transparent

In addition, you can create rectangles by using the Canvas RenderingContext2D. rect () path method in Canvas. This method needs to draw a filled rectangle with Canvas RenderingContext2D. fill () and a filled rectangle with Canvas RenderingContext2D. stroke (). In addition, we can draw rectangle directly by using the method of drawing path of Canvas. Let's first see how to use the path to draw a rectangle.

Path Drawing Rectangle

Remember when we learn to draw line segments, we know that moveTo() and lineTo() can draw line segments, so that four lines can form a rectangle, and then fill() and stroke() can draw filling and border rectangles.

function drawScreen () {
    ctx.strokeStyle = '#00';
    ctx.fillStyle = '#9f9'
    ctx.lineWidth = 4;
    ctx.beginPath();
    ctx.moveTo(30,30);
    ctx.lineTo(230,30);
    ctx.lineTo(230,200);
    ctx.lineTo(30,200);
    ctx.lineTo(30,30);
    ctx.stroke();

    ctx.beginPath();
    ctx.moveTo(300,30);
    ctx.lineTo(500,30);
    ctx.lineTo(500,200);
    ctx.lineTo(300,200);
    ctx.lineTo(300,30);
    ctx.fill();

}

In Canvas, we have a closePath() method. When drawing a rectangle, by using this method, we can close the starting point and draw the corresponding rectangle by drawing three line segments. Based on the above example, add closePath() before stroke() and fill():

function drawScreen () {
    ctx.strokeStyle = '#00';
    ctx.fillStyle = '#9f9'
    ctx.lineWidth = 4;
    ctx.beginPath();
    ctx.moveTo(30,30);
    ctx.lineTo(230,30);
    ctx.lineTo(230,200);
    ctx.lineTo(30,200);
    ctx.closePath();
    ctx.stroke();

    ctx.beginPath();
    ctx.moveTo(300,30);
    ctx.lineTo(500,30);
    ctx.lineTo(500,200);
    ctx.lineTo(300,200);
    ctx.closePath();
    ctx.fill();

}

rect() Draws a rectangle

rect() is also a method of path in Canvas. As mentioned earlier, it also needs to cooperate with fill() and stroke(). rect() has four parameters:

rect(x, y, width, height)

Where x and y are the coordinate points of the upper left corner of the rectangle, width is the width of the rectangle, height is the height of the rectangle. Next, see how rect() can be used to draw rectangles:

function drawScreen () {
    ctx.strokeStyle = '#00';
    ctx.fillStyle = '#9f9'
    ctx.lineWidth = 4;

    ctx.beginPath();
    ctx.rect(30,30,200,200);
    ctx.stroke();

    ctx.beginPath();
    ctx.rect(300,30,200,200);
    ctx.fill();

}

fillRect() Draws Filled Rectangles

The first two methods are to draw filler and border rectangle by Canvas's path method. In Canvas, you can draw a rectangle directly by fillRect():

fillRect(x,y,width,height)

Like rect(), x and y are coordinate points in the upper left corner of the rectangle, width is rectangular width, height is rectangular height:

function drawScreen () {
    ctx.fillStyle = '#9f9'
    ctx.fillRect(30,30,200,200);   
}

StrkeRect () Draws Border Rectangles

strokeRect() is similar to fillRect(), except that strokeRect() draws a border rectangle:

function drawScreen () {
    ctx.lineWidth = 4;
    ctx.strokeStyle = '#9f9'
    ctx.strokeRect(30,30,200,200);   
}

Draw rectangles with border and fill colors at the same time

What we saw earlier was a separate drawing of borders or filled rectangles. Combining the two together, we can easily draw rectangles with both border and fill colors.

function drawScreen () {
    ctx.lineWidth = 4;
    ctx.fillStyle = "orange";
    ctx.strokeStyle = '#9f9'

    // Methods #1
    ctx.beginPath();
    ctx.moveTo(10,10);
    ctx.lineTo(110,10);
    ctx.lineTo(110,110);
    ctx.lineTo(10,110);
    ctx.closePath();
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(12,12);
    ctx.lineTo(108,12);
    ctx.lineTo(108,108);
    ctx.lineTo(12,108);
    ctx.closePath();
    ctx.fill();

    // Methods #2
    ctx.beginPath();
    ctx.rect(120,10,100,100);
    ctx.closePath();
    ctx.stroke();
    ctx.beginPath();
    ctx.rect(122,12,96,96);
    ctx.fill();

    // Methods #3
    ctx.strokeRect(240,10,100,100);
    ctx.fillRect(242,12,96,96);
}

Draw a folded or rounded rectangle

I'm learning Canvas Linetype In this section, you know that in Canvas, lineJoin can change the shape of the end point of the line segment connection. If we want to draw a rectangle with a corner or a rectangle with a rounded corner, we need to use the line Join property. One thing to note, however, is that lineJoin is only suitable for style control of line segment connection contacts. That is to say, it is only suitable for the rectangle of the border, and it will not work if there is no rectangle of the border. In other words, if you need a filling rectangle with folded or rounded corners, you need to add a border on the filling rectangle with the same filling color.

 function drawScreen () {
    ctx.lineWidth = 10;
    ctx.strokeStyle = '#f99'

    ctx.lineJoin = "bevel";
    ctx.strokeRect(10,10,200,200);

    ctx.lineJoin = "round";
    ctx.strokeRect(250,10,200,200);
}

On the basis of the above examples, adjust:

function drawScreen () {
    ctx.lineWidth = 10;
    ctx.fillStyle = "#f36";
    ctx.strokeStyle = '#f36';

    ctx.lineJoin = "bevel";
    ctx.strokeRect(10,10,200,200);
    ctx.fillRect(15, 15,190,190);

    ctx.lineJoin = "round";
    ctx.strokeRect(250,10,200,200);
    ctx.fillRect(255, 15,190,190);

}

Change the Rectangle Style

Whether you use the path method in Canvas or the API that draws the rectangle, you can style the rectangle by fillStyle and strokeStyle, such as filling color and border color.

Clear Rectangles

In Canvas, there is a clearRect() that specifies how all pixels in a rectangular area (starting from point (x, y) and in the range (width, height)) become transparent and erase all previously drawn contents:

ctx.clearRect(x, y, width, height);

For example, sometimes you need to clear the canvas, you can use it like this:

ctx.save();
ctx.clearRect(0, 0, canvas.width, canvas.height);

Drawing Rectangles through JS

The previous lesson was to draw rectangles using the API of Canvas. Most of the time, we want to drag and draw a rectangle on the Canvas canvas directly with the mouse. Next, use your own crappy JavaScript to do this.

Step 1: Listen for mouse events on the canvas

Mouse events on canvas can be monitored by addEventListener(), such as mousedown, mouseup and mousemove, etc.

myCanvas.addEventListener('mousedown', mouseDown, false);
myCanvas.addEventListener('mouseup', mouseUp, false);
myCanvas.addEventListener('mousemove', mouseMove, false);

When we write mouseDown, mouseUp and mouseMove functions, we first declare two variables:

var rect = {},
    drag = false;

Step 2: Write the mouseDown() function

The mouseDown() function is what you need to do to listen for the mouse to press on the canvas:

function mouseDown(e) {
    rect.startX = e.pageX - this.offsetLeft;
    rect.startY = e.pageY - this.offsetTop;
    drag = true;
}

When the mouse is pressed, the function mouseDown() locates e by e.pageX and e.pageY, and subtracts the distance from the left and top of the Canvas canvas. Finally, set drag to true.

Step 3: Write the mouseUp() function

function mouseUp(){
    drag = false;
}

This function is very simple. When the user releases the mouse, drag to set back false. Indicates that the mouse cannot be dragged.

Step 4: Write the mouseMove() function

function mouseMove(e) {
    if (drag) {
        rect.w = (e.pageX - this.offsetLeft) - rect.startX;
        rect.h = (e.pageY - this.offsetTop) - rect.startY ;
        ctx.clearRect(0,0,myCanvas.width,myCanvas.height);
        drawRect("fill");
    }
}

The mouseMove() function is the key step. In the mouseMove() function, drag is first detected. If true, it means that you want to draw a rectangle. If false, it means that the user only moves the mouse on the canvas, and does not want to draw a rectangle. If drag is true, calculate the width and height of the rectangle by the mouse follow position. To do this, we need to subtract the current position of the mouse. This gives you the width and height of the rectangle you want to draw, but before drawing, you need to clean up the Cavans canvas through the clearRect() method. Then the drawRect() function that draws the rectangle is called.

Step 5: Draw a rectangle

function drawRect(style){
    if (style==="fill"){
      ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
    }
    if (style==="stroke"){
      ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
    }
}

The drawRect() function actually draws a rectangle, in which a style parameter is passed. If fill draws a filling rectangle, if stroke draws a border rectangle.

The effect came out. You can change the passed parameter "fill" to "stroke" to draw a rectangle with only a border.

summary

This paper introduces several methods of drawing rectangle in Canvas.

  • Drawing rectangles using the paths moveTo(), lineTo(), fill() and stroke() in Canvas
  • Drawing rectangles using rect(x,y,width,heihgt) in Canvas with fill() and stroke()
  • Draw a filled rectangle using fillRect(x,y,width,height)
  • Draw a border rectangle using strokeRect(x,y,width,height)

You can also clear the canvas by clearRect(x,y,width,height). In Canvas, besides rectangles, there are circles and so on. In the next section, we will learn how to draw circles in Canvas.

Copyright belongs to the author.
For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
Original: http://www.w3cplus.com/canvas/drawing-rectangular.html © w3cplus.com Copyright belongs to the author.

Individuals have set up front-end learning groups, aiming at learning front-end together. Pure, pure technical discussion, non-front-end personnel do not disturb! Join the crowd and add me WeChat: iamaixiaoxiao.

Keywords: Javascript

Added by MaTT on Thu, 18 Jul 2019 02:46:14 +0300