Ten minutes to learn canvas

One sentence description: canvas is an element added by HTML5 to draw 2D images and text.

Base

Simple steps:

  1. var c = document.getElementById("mycanvas"); get dom
  2. var ct = c.getContext("2d"); get 2D context
  3. ct.fillStyle = "red"; Determine the drawing style (fill/stroke)
  4. ct.fillRect(0,0,50,50); Determine the drawing position and size, the first two parameters represent the xy coordinates of the starting point, and the last two parameters represent the width and height

Drawing method:

  The 2D context provides two basic operations.

  1. Fill. fillStyle to determine, fillRect to determine the position and size.

  2. Stroke. strokeStyle to determine, strokeRect to determine the position and size.

Example 1: Draw a square

 //with border

// In HTML

<canvas id="mycanvas" width="200" height="200"></canvas>

//in js

var c = document.getElementById("mycanvas");
var ct = c.getContext("2d");
ct.fillStyle = "aqua";
ct.fillRect(0,0,50,50);
ct.strokeStyle = "red";
ct.strokeRect(0,0,50,50);

Well, the most basic operations have been learned, and continue to go down.

primary:

clearRect():

  Can be used to clear the contents of the canvas.

Example 2: Draw two squares, the middle part is empty

var c = document.getElementById("mycanvas");
var ct = c.getContext("2d");
ct.fillStyle = "aqua";
ct.fillRect(0, 0, 50, 50);
ct.fillStyle = "red";
ct.fillRect(30, 30, 50, 50);
ct.clearRect(30, 30, 20, 20);

Note that the actual position of clearRect starts from the upper left corner.

draw the clock

 to be continued. .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324989807&siteId=291194637