Official Document link

Basic steps for drawing graphics

  1. Gets the canvas and gets the context
  2. Create the starting point, draw the path, and close the path
  3. Perform various operations in the specified area
const canvas = document.getElementById('tutorial'); 
const ctx = canvas.getContext('2d'); // Note: 2d lowercase, 3d: webgl

/ / scaling of class
ctx.translate(75.75);

/ / style classes
ctx.fillStyle = '#09F';

ctx.beginPath();
ctx.moveTo(130.50); / / starting point

// Draw the region
ctx.lineTo(150.75); 
ctx.arc(0.0.60.0.Math.PI*2.true);

ctx.closePath();

/ / function
ctx.fillRect() // Fill draw
ctx.stroke(); // Draw a border
ctx.clip(); / / cutting
ctx.clearRect(x, y, width, height) // Clear region: Essentially set this region color to transparent, rGBA (0,0,0)
Copy the code

Drawing graphics class

  1. Draw the linelineTo(x, y)
  2. Draw the arcarc(x, y, radius, startAngle, endAngle, anticlockwise)
  • Angle generally adoptsMath. PI * degree
  • anticlockwisTrue: counterclockwise, false: clockwise

Style class

  1. Fill colorfillStyle = color
  2. Outline of the colorstrokeStyle = color
  3. Set overall transparencyGlobalAlpha = 0.2
  4. Line widthlineWidth = value
  5. Sketch, draw line end style, joint style, virtual style

The text class

  1. Fill the text at the specified locationfillText(text, x, y [,maxWidth])
  2. Draws border text at the specified positionstrokeText(text, x, y [,maxWidth])
  3. The text stylefont = value, text on its waytextAlign = value, baseline alignmenttextBaseline, text directiondirection

The image class

  1. Image elementdrawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
  • Image: Image DOM element
  • Sx, SY: drawing position
  • SWidth, sHeight: Draw width and height, such as half the height of the original image, image.naturalWidth * 0.5
  • Dx, dy,dWidth, dHeight, the clipping properties above the original image

Deformation class

  1. Move the canvas origin (0, 0)translate(x, y)
  2. Rotate the canvasrotate(Math.PI)
  3. Zoom the canvasscale(x, y)

Functional class

  1. Save all the current states of the canvas (font color, thickness, etc.)save()
  2. Restore all states of the last save(),restore()
  3. Cutting pathclip()
  • The difference with normal images: just a mask, the content of the canvas outside the region is not rendered
  1. Determine whether a coordinate point is in a regionctx.isPointInPath((path, x, y, fillRule);)
  • path = new Path2D(); path.rect(50, 200, 200, 200); ctx.fill(path);

Event classes

  1. Canvas global eventcanvas.addEventListener('mouseover', callback)

The animation process

  1. Empty canvas
  2. Save the initial state
  3. Draw new content (new frame)
  4. Restore initial state
  5. Open the next frame
  6. Correlation functionwindow.requestAnimationFrame(func).setInterval().setTimeout()
const ctx = document.getElementById('canvas').getContext('2d');
ctx.clearRect(0.0.300.300); // Empty the canvas

ctx.fillStyle = 'rgba (0,0,0,0.4)';
ctx.save(); // Save the initial state

// Draw the content of the moment

ctx.restore(); // Restore the initial state

window.requestAnimationFrame(draw); // Open the next frame
Copy the code

Actual combat case classThe connection

Click on a graphic and change its color

const colorArr = ['red'.'blue'.'yellow'.'orange'.'pink'];
let idx = 0;
const canvas = document.getElementById('tutorial');
const ctx = canvas.getContext('2d');
const path1 = new Path2D();
const path2 = new Path2D();
path1.rect(50.50.200.200);
path2.rect(300.50.200.200);
ctx.fill(path1);
ctx.fill(path2);

canvas.addEventListener('click'.(e) = > {
  const canvasInfo = canvas.getBoundingClientRect();
  console.log(ctx.isPointInPath(e.clientX - canvasInfo.left,
    e.clientY - canvasInfo.top));

  ctx.save();
  ctx.fillStyle = colorArr[idx % colorArr.length];
  idx++;
  ctx.fill(path1);
  ctx.restore();
});
Copy the code

Canvas compressed image

const rawImg = document.getElementById('rawImg');
const compressImg = document.getElementById('compressImg');

const canvas = document.getElementById('canvas-compress');
const ctx = canvas.getContext('2d');

const compressradix = 0.0000001; // Compression coefficient
const scale = 0.5; // Image size scaling multiple

ctx.drawImage(rawImg, 0.0, rawImg.width * scale, rawImg.height * scale);

QualityArgument specifies the quality of the exported image. This parameter is valid only if the exported image is in JPG or webp format. The default value is 0.92
compressImg.src = canvas.toDataURL('image/jpg', compressradix);
canvas.toBlob((blob) = > {
  console.log(blob)
}, 'image/jpg', compressradix);
Copy the code