Canvas is a tag provided by HTML5 for displaying drawing effects. Canvas is a Canvas used to display drawing effects in HTML pages. Canvas was originally proposed by Apple and has been implemented in most browsers today.

Canvas usage domain

  • The game
  • Big data visualization data
  • Banner ads
  • multimedia
  • simulation
  • Remote operation
  • Graphics editor

Check whether the browser supports the Canvas tag

var canvas = document.getElementById('canvas')
if (canvas.getContext) {
  console.log('Your browser supports Canvas! ')}else {
  console.log('Your browser doesn't support Canvas! ')}Copy the code

Basic usage of Canvas

1. Using the Canvas tag, you can open up a grid area in the page. You can set its width and height to 300 and 150

<canvas></canvas>
Copy the code

2. Get the DOM element canvas

Canvas itself cannot draw. The Canvas object provides various apis for drawing.

var cas = document.querySelector('canvas')
Copy the code

3. Get the context object (canvas object!) via CAS.

var ctx = cas.getContext('2d')
Copy the code

4. Start drawing with CTX (Set the starting point and finishing line – Stroke)

ctx.moveTo(10.10)
ctx.lineTo(100.100)
ctx.stroke()
Copy the code

Draw lines

  • Set the starting position:context.moveTo( x, y )
  • Set end position:context.lineTo( x, y )
  • Stroke drawing:context.stroke()
  • Fill drawing:context.fill()
  • Closed path:context.closePath()

Canvas can also set properties related to lines as follows:

  • CanvasRenderingContext2D.lineWidthSet the line width.
  • CanvasRenderingContext2D.strokeStyleSets the line color.
  • CanvasRenderingContext2D.lineCapSet the line end type, ‘butt'(default), ’round’, ‘square’.
  • CanvasRenderingContext2D.lineJoinSet the inflection point of intersecting lines, ‘miter'(default), ’round’, ‘bevel’,
  • CanvasRenderingContext2D.getLineDash()Gets an array of line segment styles.
  • CanvasRenderingContext2D.setLineDash()Sets the line segment style.
  • CanvasRenderingContext2D.lineDashOffsetDraws a line segment offset.

Encapsulate a method to draw a rectangle

function myRect(ctxTmp, x, y, w, h) {
  ctxTmp.moveTo(x, y)
  ctxTmp.lineTo(x + w, y)
  ctxTmp.lineTo(x + w, y + h)
  ctxTmp.lineTo(x, y + h)
  ctxTmp.lineTo(x, y)
  ctxTmp.stroke()
}

var cas = document.querySelector('canvas')
var ctx = cas.getContext('2d')
myRect(ctx, 50.50.200.200)
Copy the code

Draw a rectangle

  • fillRect( x , y , width , height)Fill rectangles starting with (x,y) width and height with black by default
  • stokeRect( x , y , width , height)Draw a hollow rectangle starting with (x,y) width and height respectively
  • clearRect( x, y , width , height )Clear the rectangle starting from (x,y) width and height to transparent

Draw the arc

There are ways to draw an arc

  • CanvasRenderingContext2D.arc()
  • CanvasRenderingContext2D.arcTo()

6 parameters: x, y(coordinates of the center of the circle), radius, starting radian (not Angle deg), ending radian, (bool set direction!)

var cas = document.querySelector('canvas')
var ctx = cas.getContext('2d')

ctx.arc(100.100.100.0, degToArc(360))
ctx.stroke()

// The Angle turns radians
function degToArc(num) {
  return (Math.PI / 180) * num
}
Copy the code

Drawing fan

var cas = document.querySelector('canvas')
var ctx = cas.getContext('2d')

ctx.arc(300.300.200, degToArc(125), degToArc(300))

// automatically connect to the origin
ctx.closePath()
ctx.stroke()

function degToArc(num) {
  return (Math.PI / 180) * num
}
Copy the code

Make the brush

  1. Declare a variable as an identifier
  2. When the mouse is pressed down, record the starting position
  3. As the mouse moves, start drawing and connecting
  4. When the mouse is up, turn off the switch

Click to see the renderings

var cas = document.querySelector('canvas')
var ctx = cas.getContext('2d')

var isDraw = false
// Mouse down event
cas.addEventListener('mousedown'.function () {
  isDraw = true
  ctx.beginPath()
})

// Mouse movement events
cas.addEventListener('mousemove'.function (e) {
  if(! isDraw) {// Not pressed
    return
  }
  // Get the coordinates relative to the container
  var x = e.offsetX
  var y = e.offsetY
  ctx.lineTo(x, y)
  ctx.stroke()
})

cas.addEventListener('mouseup'.function () {
  // Turn off the switch!
  isDraw = false
})
Copy the code

Manual inunction

The principle is similar to canvas, but with the clearRect() method.

Click to see the renderings

var cas = document.querySelector('canvas')
var ctx = cas.getContext('2d')

ctx.fillRect(0.0.600.600)

/ / switch
var isClear = false

cas.addEventListener('mousedown'.function () {
  isClear = true
})

cas.addEventListener('mousemove'.function (e) {
  if(! isClear) {return
  }
  var x = e.offsetX
  var y = e.offsetY
  var w = 20
  var h = 20
  ctx.clearRect(x, y, w, h)
})

cas.addEventListener('mouseup'.function () {
  isClear = false
})
Copy the code

Scratch music

  1. First you need to set up the prize and the canvas, put the canvas on top of the picture to cover,
  2. Random Settings generate prizes.
  3. As the touch moves, part of the canvas can be erased to reveal the prize area.

Click to see the renderings

<div>
  <img src="./images/2.jpg" alt="" />
  <canvas width="600" height="600"></canvas>
</div>
Copy the code

css

img {
  width: 600px;
  height: 600px;
  position: absolute;
  top: 10%;
  left: 30%;
}

canvas {
  width: 600px;
  height: 600px;
  position: absolute;
  top: 10%;
  left: 30%;
  border: 1px solid # 000;
}
Copy the code

js

var cas = document.querySelector('canvas')
var ctx = cas.getContext('2d')
var img = document.querySelector('img')
// Add a mask layer
ctx.fillStyle = '#ccc'
ctx.fillRect(0.0, cas.width, cas.height)
setImgUrl()
/ / switch
var isClear = false
cas.addEventListener('mousedown'.function () {
  isClear = true
})
cas.addEventListener('mousemove'.function (e) {
  if(! isClear) {return
  }
  var x = e.offsetX
  var y = e.offsetY
  ctx.clearRect(x, y, 30.30)
})
cas.addEventListener('mouseup'.function () {
  isClear = false
})

function setImgUrl() {
  var arr = ['./images/1.jpg'.'./images/2.jpg'.'./images/3.jpg'.'./images/4.jpg']
  / / 0 to 3
  var random = Math.round(Math.random() * 3)
  img.src = arr[random]
}
Copy the code

For more demos, see github.com/Michael-lzg…

Recommend the article

Build a VuE-CLI4 + WebPack mobile framework (out of the box)
Build from scratch to optimize a vue-CLI-like scaffolding
Encapsulate a TOAST and Dialog component and publish it to NPM
Build a WebPack project from scratch
Summary of several webpack optimization methods
Summary of advanced application of VUE knowledge system
Summarize the practical skills of vUE knowledge system
Summarize the basic introduction to vUE knowledge system
Summary of mobile H5 development tips.

Concerned about my public number irregularly share front-end knowledge, progress with you!