Canvas learning
Canvas advantages
- is
html5
The proposed new TAB can be used for games- Lightweight canvas, you can use JS directly to do processing, no need to add additional plug-ins, good performance, no lag, in the mobile phone is also very smooth
Canvas shortcomings
- Draw a graph. Once it is successfully drawn, it will be pixelated, that is, the canvas cannot get the graph again, and it will be modified
- Solution: Canvas graphics must be moved according to the logic of clear > Update > Render
Version compatibility problem: If Internet Explorer 6, 7, and 8 are incompatible, you can write prompt text in the label to distinguish them. Compatible browsers do not display prompt text
The basic use
- Create canvas:
<canvas height="200" width="400" id="myCanvas">The current browser version is not supported. Upgrade the browser</canvas>
Copy the code
The width can be set directly by height and width (no unit required), or by CSS, but the ID attribute is distorted to uniquely position the canvas
- Get canvas:
let canvas = document.getElementById("myCanvas") // Get the canvas
let ctx = canvas.getContext("2d") // Set the canvas environment
Copy the code
All image drawing is set based on Canvas.getContext (“2d”), regardless of the Canvas tag
- Canvas based drawing: coordinate origin in upper left corner
/ / fill
ctx.fillStyle='red' // Set the color
ctx.fillRect(100.200.300.400) // Draw the image
/ / to draw
ctx.strokeStyle = "grend"
ctx.strokeRect(left,120.100.100)
/ / path
ctx.beginPath() // Create a path
ctx.moveTo(100.200)// Sets the initial drawing point
ctx.lineTo(200.300)// Draw the path
ctx.lineTo(180.360)
ctx.lineTo(80.380)
ctx.lineTo(140.330)
ctx.closePath()// Close the path
ctx.strokeStyle = "yellow"// Render the color of the drawn path
ctx.stroke() // Draw the path
/ / arc
ctx.beginPath()
ctx.arc(100.100.80.0.4.false)
/ / in a straight line
ctx.globalAlpha = 0.3 // The line is transparent, between zero and one
ctx.lineWidth = 3 // Set the line thickness
ctx.lineCap = "butt" // Set the styles on both ends of the unenclosed line
ctx.lineJoin = "miter" // Set the style at the fold point of the line
ctx.setLineDash = ([1.2.3.4]) // Set the dashed line segment style
ctx.strokeRect(20.20.100.100) // The dotted lines above form the rectangle
ctx.lineDashOffset = 2 // Offset to the left by 2
// Draw text
ctx.textAlign="center" // Center and align
ctx.strokeText("Hello...".0.100); // Draw content at the specified position
// Linear gradient
let lnear = ctx.createLinearGradinent(0.0.100.100) // Gradient direction
lnear.addColorStop(0."red") // Set the proportional color
ctx.fillStyle = lnear // Render the corresponding color
/ / the shadow
ctx.shadowOffsetX = 2 // The shadow's x offset is 2
ctx.shadowOffsetY = 2 // The y offset of the shadow is 2
ctx.shadowBlur = 10 // The shadow has a blur of 10
ctx.shadowColor = "red" // The shadow color is red
/ / picture
let image = new Image() // instantiate the image object
image.src = "Picture address" // Assign an address to the instance
image.onload = function(){ // Listen for image loading events
ctx.drawImage(image,1.2.3.4.5.6.7.8) // start at 1,2 and place the slices at 5,6 on the canvas. Set the width to 7 and the height to 8
}
Copy the code
fill
ctx.fillStyle="color"
: Draws graphic fill colorCtx.fillrect (x axis,y axis,width,height)
: Draws the fill rectangledraw
ctx.strokeStyle = "color"
: Draws the color of the borderCtx.strokerect (x axis,y axis,width,height)
: Draws a hollow rectangleThe path
ctx.beginPath()
: Creates a path to draw an irregular graphctx.moveTo(x,y)
: The starting point for creating a drawing pathctx.lineTo(x,y)
: Creates the coordinates of the second point and all points, and joins them in sequencectx.closePath()
: After drawing the path, connect the starting point with the position of the last point,Form a closed patternctx.strokeStyle = "yellow"
: Colors the paths that have been drawnctx.fillStyle="color"
: or fill the rendered color of the drawn pathctx.stroke()
: instantiates the pathctx.fill()
: instantiates the fill pathThe circular arc
ctx.arc(x,y,redius,starAngle,endAngle,anticlockwise)
: Draw arc – Fill- X and y: indicates the center position of the circle
- Redius: indicates the radius
- StartAngle: indicates the starting position (3.14 is π, one radian),
- EndAngle: indicates the end position (also π)
- Anticlockwise: anticlockwise: anticlockwise
A straight line
CTX. GlobalAlpha = 0.3
: Transparent for drawing a line, ranging from 0 to 1ctx.lineWidth = number
: Sets the thickness of a line. There is no unit. The default is onectx.lineCap = "butt"
: Sets the style of the exposed end of the line, optional (“butt”,”round”,”square”), the ‘square’ ends will extend by half the widthctx.lineJoin = "miter"
: Sets the style where the two lines meet. Optional values (“rund”,”bevel”,”miter”)Ctx.setlinedash = ([array])
: Receives an array of numbers whose values and order represent the dashed line’s length ratio, and at least two argumentsctx.strokeRect(x,y,width,height)
: configuration, using the upper dotted line segmentctx.lineDashOffset = 2
: Sets the offset from the dashed lineDraw text
ctx.textAlign="center"
: Sets the alignment of text within the drawing rangeCtx. strokeText(" text content ", x, y);
: x, y: indicates the starting position of the drawingLinear gradient
let lnear = ctx.createLinearGradinent(x1,y1,x2,y2)
: x1, y1: represents the starting point of drawing; X2, y2: indicates the drawing end pointlnear.addColorStop(num,"color")
:num: the value ranges from 0 to 1. Multiple colors are proportionally divided. Color: indicates the color of the corresponding endctx.fillStyle = lnear
: Render the corresponding colorRadial gradient
ctx.createRadialGradient(x1,y1,r1,x2,y2,r2)
:x1, y1, r1: parameters to start a circle, x2, y2, r2: parameters to end a circleshadow
ctx.shadowOffsetX = num
: Shadow direction — X-axisctx.shadowOffsetY = num
: Shadow direction — y axisctx.shadowBlur = num
: Shadow blurctx.shadowColor = "color"
: Shadow colorThe picture
let image = new Image()
: Create an imageImage.src = "image.src"
: Introduces the image addressimage.onload = function(){}
: Execute immediately after the image is loadedctx.drawImage(image,e,f,j,h,a,b,c,d)
: in the onload event, can write two parameters, four parameters, eight parameters
- A, B: indicates the initial position of the picture, that is, the position of X-axis and Y-axis
- C, D: indicates the width and height of the picture
- E, f: indicates the starting point of cutting the picture
- J, H: indicates the width and height of slices
- When there are only two or four parameters, take a, b, c, and D
- The basics of animation implementation:
ctx.clearRect(0.0,canvas.width,canvas.height) // Clear the screen
Copy the code
Ctx.clearrect (x,y,width,height) : x and y represent the position where the clearance begins,width and height represent the width and height of the clearance
- Set up a full-screen canvas
canvas.width = document.documentElement.clientWidth-30 ; // Subtract 30 to get rid of the scroll bar
canvas.height = document.documentElement.clientHeight -30 ;
Copy the code
- Any direction
this.dx = parseInt(Math.random()*10) -5
this.dy = parseInt(Math.random()*10) -5
Copy the code
The animation to learn
- Simple animation implementation
let canvas = document.getElementById("myCanvas")
let ctx = canvas.getContext("2d")
ctx.fillStyle='red'
let left = 100 // The initial left distance position
setInterval(() = >{
ctx.clearRect(0.0,canvas.width,canvas.height) / / clear screen
left++; // The distance to the left
ctx.fillRect(left,100.100.100) // Repeat the drawing
left>600? left = -100:left; // clear the left distance
})
Copy the code
- Animate with object-oriented thinking
- Prepare the parameters on the function prototype object
function rects(x,y,w,h,color) {// Initial state
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.color = color;
}
// Set the method on the prototype
/ / update
rects.prototype.updata = function () {
this.x++
}
/ / rendering
rects.prototype.render = function () {
ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.w,this.h);
}
Copy the code
- Instantiate an object
let r1 = new rects(100.30.50.50."red")
Copy the code
- The animation process
setInterval(() = >{
/ / clear screen
ctx.clearRect(0.0,canvas.width,canvas.height)
r1.updata();
r1.render()
},10)
Copy the code
Animation case
Colorful ball case
const ballArr = [] ; // Create an array to store instances
function Ball(x,y,r){
this.x = x ; // Set the x coordinates
this.y = y ; // Set the left side of the y axis
this.r = r ; // Set the radius of the circle
this.color = getRandom() ; // Set the small circle color -- random y
this.dx = parseInt(Math.random()*10) -5 ; // Set the x direction
this.dy = parseInt(Math.random()*10) -5 ; // Set the y direction
ballArr.push(this);// Store the generated balls in the array
}
// Render ball -- Create a shape and render it
Ball.prototype.render = function () {
ctx.beginPath()
ctx.arc(this.x,this.y,this.r,0.Math.PI*2.false)
ctx.fillStyle = this.color
ctx.fill()
}
// Set the mouse monitor event -- creates a small ball when the mouse moves
canvas.addEventListener("mousemove".function (event) {
new Ball(event.offsetX,event.offsetY,30)})// The movement direction of the ball and the change of movement time -- decrease
Ball.prototype.updata = function () {
this.x += this.dx;
this.y += this.dy;
this.r -= 0.1
if (this.r < 0) {// If the radius is less than zero, execute the delete command to delete it from the array
this.remove(); }}// If the radius is smaller than a certain value, delete the radius
Ball.prototype.remove = function () {
for (let i = 0 ; i < ballArr.length ; i++){
if (ballArr[i] == this){
ballArr.splice(i,1)}}}// Timer for animation render and update
setInterval(function () {
ctx.clearRect(0.0,canvas.width,canvas.height)
for (let i = 0 ; i < ballArr.length; i++){
ballArr[i].updata()
if (ballArr[i]){
ballArr[i].render()
}
}
},10)
// Randomly generate colors
function getRandom() {
let allTypeArr = ["0"."1"."2"."3"."4"."5"."6"."Seven"."8"."9"."a"."b"."c"."d"."e"."f"]
let color = "#"
for (let i = 0 ; i < 6 ; i++){
let random = parseInt(Math.random()*allTypeArr.length)
color += allTypeArr[random]
}
return color
}
Copy the code
Case study of ball connection
let canvas = document.getElementById("myCanvas")
let ctx = canvas.getContext("2d")
// Set the full screen width
canvas.width = document.documentElement.clientWidth-30
canvas.height = document.documentElement.clientHeight -30
function Ball() {
// Set the point at which the ball appears -- any
this.x = parseInt(Math.random() * canvas.width)
this.y = parseInt(Math.random() * canvas.height)
this.r = 10
this.color = getRandom()
// Set the direction of the ball - any
this.dx = parseInt(Math.random()*10) -5
this.dy = parseInt(Math.random()*10) -5
// Store the generated ball
ballArr.push(this)
// Record your value in the array
this.index = ballArr.length-1;
}
// The ball is moving in the same direction
Ball.prototype.update = function () {
this.x += this.dx;
this.y += this.dy;
if (this.x < this.r || this.x > canvas.width-this.r){
this.dx = -this.dx;
}
if (this.y < this.r || this.y > canvas.height-this.r){
this.dy = -this.dy; }}// Ball render
Ball.prototype.render = function () {
ctx.beginPath()
ctx.globalAlpha = 1 / / transparency
/ / ball
ctx.arc(this.x,this.y,this.r,0.Math.PI*2.false)
ctx.fillStyle = this.color;
ctx.fill()
/ / line
for (let i = this.index ; i < ballArr.length ; i++){
if (Math.abs(ballArr[i].x-this.x)<150 && Math.abs(ballArr[i].y - this.y) < 150){
ctx.strokeStyle = getRandom();
ctx.beginPath();
ctx.globalAlpha = 10/Math.sqrt(Math.pow(ballArr[i].x-this.x ,2) +Math.pow(ballArr[i].y -this.y,2))// Connect the transparency between the balls
ctx.moveTo(this.x,this.y);
ctx.lineTo(ballArr[i].x,ballArr[i].y)
ctx.closePath()
ctx.stroke()
}
}
}
let ballArr = []
for (let i = 0 ; i < 30 ; i++){
new Ball()
}
setInterval(function () {
ctx.clearRect(0.0,canvas.width,canvas.height)
for (let i = 0; i < ballArr.length ; i++){ ballArr[i].update() ballArr[i].render(); }})function getRandom() {
let allTypeArr = ["0"."1"."2"."3"."4"."5"."6"."Seven"."8"."9"."a"."b"."c"."d"."e"."f"]
let color = "#"
for (let i = 0 ; i < 6 ; i++){
let random = parseInt(Math.random()*allTypeArr.length)
color += allTypeArr[random]
}
return color
}
Copy the code