This is the 11th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021

Canvas The canvas element is used for drawing graphics, which is done by script (usually JavaScript). You can use canvas to draw paths, boxes, circles, characters, and add images in a variety of ways.

Create a canvas

The canvas tag defaults to 300px width and 150px height; Ids on the same page cannot be duplicated

<canvas type="2d" id="myCanvas"></canvas>
Copy the code

Setting the size of the canvas directly using CSS will cause the canvas to scale to the values you set.
When I draw a 100*100 square directly, it shows a rectangle

The last temporary solution is to change the canvas size with CSS Settings like this, and then it is scaled, so we will re-set canvas.width=”300″ in js; canvas.height=”500″; You can go back to normal

So why don’t we move on to how do we draw this square

Draw squares

Create a canvas

<canvas type="2d" id="myCanvas" style="height: 500px; width: 300px;">
</canvas>
Copy the code

Js starts painting. Before, we said id is unique, because we get canvas element according to ID, wechat applet cannot use document, we need to use wx.createsElectorQuery () instead

 const query = wx.createSelectorQuery()
   query.select('#myCanvas')
     .fields({ node: true.size: true })
     .exec((res) = > {
       const canvas = res[0].node
       canvas.width="300";
       canvas.height="500";
       The getContext() method returns an environment to draw on the canvas.
       const ctx = canvas.getContext('2d') 🎈 Set the style before painting// fillRect draws squares: x, Y,w,h default color black
       // Set the fill color
       // ctx.fillStyle = 'yellow';
       
       // Create a gradient color
       var c =ctx.createLinearGradient(0.200.200.0);
       c.addColorStop(0."yellow");
       c.addColorStop(1."red");
       // Fill the gradient colorctx.fillStyle=c; 🎈 Canvas is a two-dimensional grid. The upper-left coordinate of canvas is (0.0)
       // draw a 100x100 square on the canvas, starting at the top left corner (0,0)
       ctx.fillRect(0.0.100.100);
       
       // strokeRect draws a box with a border. The default border size is 1px
       // Set the border width
       ctx.lineWidth = 10;
       // Set the border color
       ctx.strokeStyle = 'red'
       // Set the border Angle style
       // lineJoin: miter(rectangular, default), round (round), bevel (bevel)
       ctx.lineJoin = 'round';
       ctx.strokeRect(105.105.100.100);
     })
Copy the code

That’s how it ends