当前位置:网站首页>I hope to explain the basics of canvas as clearly as possible according to my ideas
I hope to explain the basics of canvas as clearly as possible according to my ideas
2022-06-25 10:11:00 【Please code】
Write it at the front
canvas Many people have written , I also wrote about in my previous blog canvas A tutorial for , But I don't think it's very good , Because many things are very vague , There is no very intuitive and clear will canvas Explain clearly , The reason is , This attribute is not used enough , As a result, many attributes are not proficient , But I hope this article can completely explain this attribute , After all, it's just a label , It wouldn't be too complicated , The reason why he is not very studious is that he has too many methods , In addition, a lot of effects require the cooperation between methods , So the difficulty and complexity are directly increased , It is not like html The same as the other labels of , such as p、span They just brought some styles with them , But there are not so many methods and properties , But when we learn it, we don't have to understand it all , and canvas In fact, there are only two properties ,width and height, Its complexity comes from its API, In fact, we only need to record and understand the basic usage of his method , It is also possible to consult documents when we really need this business , After all, energy is limited , Of course, if you have a lot of time , You can watch all the videos and documents , Try all the methods , Including some common animation combinations and so on ! Blogger, I've been busy for several nights , Wrote many examples , I also tried many techniques to show you before I finished this article , It's not too much to praise after reading ! The article is a bit long , Read slowly !
canvas Introduce
canvas yes H5 A property in the new feature , To put it bluntly , It's just one. html New label for , and div、p、span It's all the same , Can be directly parsed by the browser html Language , So we should not exclude it from our hearts , Don't be afraid of it , Let's make it a div Just come and learn !( In fact, this paragraph is my own comfort ), Why would there be canvas Well ? In fact, before he appeared , Our animations are all funny (Adobe) The company's Flash Technical support , One of his big problems is that he is heavy , I found it during installation , The installation file is actually very large , So it was gradually eliminated , so to speak canvas In fact, I gave it to Flash A heavy blow , Being backward means being beaten , normal ! But it doesn't mean canvas It is completely good , He also has some drawbacks , This chapter will briefly introduce canvas Some of the problems and features of !
canvasAPI
How to learn ?
I didn't learn this question canvas Before , Think for a long time , Although I haven't fully mastered it until the end of this article canvas Use , But I am no longer afraid of this technical point , Because I know what happened to him , This feeling may be experienced by many people , It's just a technology , You suddenly feel that he is very simple , Maybe it's just that some effects are very complicated , But not without any ideas , It just takes time to write the code , Here I'll tell you how I saw it
- The first thing to learn : He is just a HTML label
Learn a new knowledge point , It's important to understand his nature , So this is not nonsense , Someone might see it and say , Of course I know it's a label , But you never accept that he is a label , Because it's heavy , This weight is relative to the others html The label says , A normal tag is just a function block with a simple character style , So the study itself will not be too heavy ! So we learn canvas It is only a simple label to learn !
- The second point of learning : His drawing function has nothing to do with himself
This sentence is not a rebuke , It's not wrong , It itself only provides and others htm Tag like functionality , It just provides an area , As for its powerful drawing function , It's him API, It has nothing to do with his own attributes , Someone said , I'll use it directly div Why not ? So I want you to understand my first sentence , That is to say, he just provided an area , This area is for API The use of , So don't argue here , It has nothing but width and height Two attributes ! therefore , His difficulty lies only in his API On ! What we need to learn is his method , Not itself ! Most of our scenarios are based on 2d Scenario development , in other words , Whether you are familiar with it or not canvas Use , You should know how to write at the beginning ,
// Because it's all based on canvasAPI developable , So we first need to get the context of the tag to , How to implement it later , It is based on the actual business , So the best you can say is that you won't his API, You can't say you won't canvas let canvas = document.getElementById('canvas') let cas = canvas.getContext('2d')
- The third point of learning : His drawing function is based on his API
This sentence looks like some nonsense , But we try to understand , It's like we see this :
In fact, you can learn these or some of these key methods , His methods seem to be many , But in fact, many of them are very simple methods with some attributes , such as beginPath(),fill() And so on are just some methods , Even without any attribute parameter values ! So a key point is whether you have the patience to try the method attributes that appear on the document , A lot of things you just try , Will be very sure of his usage , People are afraid of the unknown , We know his essence , Nature will not fear !
- The fourth point of learning : By writing simple Demo, The process of assembling complex applications
This is a way of learning , When an application or animation looks complex to you , You just need to split the animation , for instance , The moving ball is canvas The classic drawing examples in , When I first saw it, I also felt how complicated it was , Later, I slowly studied his implementation process , The discovery is not complicated , This is a large amount of code , Take it apart , Draw a little ball 、 Let him exercise 、 Generate random numbers for the motion trace 、 Make a timer to repeat the drawing and movement 、 This seemingly complex functional application is realized , Which of the first four steps is complicated ? So I will write a few below Demo, It's very simple , Entry level canvas Of Demo, But you can use these Demo Put together some of the more complex applications you want ! below demo take canvas A few that are used more frequently in API It was demonstrated , Can run directly to your local html File to see the effect !
- The fifth point of learning : Special description of parameters
In the second point, I said that most of our scenes are based on 2d Context , But that doesn't mean he only has 2d This is a parameter ,canvas For us ’webgl’ or ’experimental-webgl’、webgl2、bitmaprenderer, These three parameters will not be introduced in detail in this article , Although these are four parameters , But the first two are the same , But the second one is IE Compatible with the first parameter , If you are interested, you can see the detailed introduction of these three parameters ! Parameter Introduction
canvas Need explicit features
canvas Compatibility is not good , Browser compatibility processing is required
We all know canvas yes H5 New features , That means , I won't support it H5 Of course, the browser version of does not support canvas, So we need to write canvas When , Write a compatibility prompt , For example, the following code :
<canvas> This browser version does not support canvas, Please upgrade your browser or use Chrome Browser open </canvas>canvas Do not have the ability to retrieve the canvas content
canvas Do not have the ability to retrieve the canvas content , Explain this sentence , After we draw a figure on the canvas , To get this graph , no ,canvas Do not have the ability to obtain this graphic , that canvas How to realize animation ? One of his ideas is more violent , By constantly clearing the screen -》 Redrawing operation to achieve animation ! To put it bluntly, it means constantly deleting the figures that have been drawn before , Redraw again , It's just that the next time is different from the last time , The process of continuously clearing the display is the process of animation , Every static graph is a frame , Write a demo, Give it a try , The drawing process will be described in detail later ! The demo Just to demonstrate canvas How to generate the animation of . Here's to say , Toby's Flash Technology can get the animation itself , This is one reason why he is heavier !
<!-- * @use: Just run the browser directly * @description: Canvas basic animation display * @SpecialInstructions: At the bottom of the Demo What happened in cas All of them Html Medium canvas * @Author: clearlove * @Date: 2022-05-28 02:26:50 * @LastEditTime: 2022-05-28 02:39:51 * @FilePath: /universal-background-template/Users/leimingwei/Desktop/ Open source code /canvas.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style> canvas {
border: 1px solid rebeccapurple; } </style>
</head>
<body>
<canvas id="cas" width="600" height="600">
This browser version does not support Canvas, Please upgrade your browser or use Chrome Browser open
</canvas>
</body>
<script> // The following example is just a demonstration js How to write the part , This is not recommended in actual development , Encapsulate every required function as much as possible let canvas = document.getElementById('cas') let ctx = canvas.getContext('2d') // Set a background color ctx.fillStyle = 'grep' // Set a unit quantity The offset of the motion let offsetLeft = 50 // Start animating setInterval(() => {
// Empty the canvas clearCanvas(ctx,0, 0, 600, 600) // Set the shift offset offsetLeft++ // Began to draw stay X Axial motion Draw a in Y Axis 300 Location ,50*50 The rectangular ctx.fillRect(offsetLeft, 300, 50, 50) }, 10) /** * @function clearCanvas Empty the canvas * @params O {String} canvas content object * @params startX {Number} Empty X Coordinate start position * @params startY {Number} Empty Y Coordinate start position * @params W {Number} Empty width * @params H {Number} Empty height * */ function clearCanvas(O, startX, startY, W, H) {
O.clearRect(startX, startY, W, H) } </script>
</html>
- Running results

- Class to modify the above code Implement a moving rectangle Demo-1 fillRect、strokeRect
let canvas = document.getElementById('cas')
let ctx = canvas.getContext('2d')
console.trace(ctx.canvas.clientWidth)
// Get canvas Width
let casWidth = ctx.canvas.clientWidth
// Declare a drawn class ( Method )X:x Axis start position 、Y:y Axis start position 、W: Graphic width 、H: Figure height 、C: The background color of the graphic
function Drawgraphics(X, Y, W, H, C) {
this.X = X
this.Y = Y
this.W = W
this.H = H
this.C = C
}
// to update X Axis position
Drawgraphics.prototype.updateLocation = function () {
this.X++
}
// Start painting the canvas
Drawgraphics.prototype.startFillRect = function () {
ctx.fillStyle = this.C
ctx.fillRect(this.X, this.Y, this.W, this.H)
}
// Draw a rectangular border
Drawgraphics.prototype.startStroke = function () {
ctx.strokeStyle = this.C
ctx.strokeRect(this.X, this.Y, this.W, this.H)
}
// Declare an instance of drawing a rectangle
let R = new Drawgraphics(50, 50, 50, 50, '#cccccc')
// Declare an instance of drawing a rectangular border
let S = new Drawgraphics(80, 80, 50, 50, '#cccccc')
// Start animating
let stopFlag = setInterval(() => {
// Empty the canvas
clearCanvas(ctx, 0, 0, 600, 600)
// Set the shift offset
R.updateLocation()
// Began to draw stay X Axial motion Draw a in Y Axis 300 Location ,50*50 The rectangular
R.startFillRect()
// Set the shift offset
S.updateLocation()
// Draw a rectangular border
S.startStroke()
// Touch the edge and stop
if(S.X >= casWidth - 50){
clearInterval(stopFlag)
}
}, 10)
// Empty the canvas { Note the above code }
function clearCanvas(O, startX, startY, W, H) {
O.clearRect(startX, startY, W, H)
}
- Running effect

- Draw irregular figures Demo-2 moveTo、lineTo
let canvas = document.getElementById('cas')
let ctx = canvas.getContext('2d')
// Create a path
ctx.beginPath()
// The starting point Move the drawing point
ctx.moveTo(50, 50)
// The position of the first point Describe the drawing path
ctx.lineTo(400, 50)
// The position of the second point
ctx.lineTo(400, 450)
// The position of the third point
ctx.lineTo(50, 150)
// Close the drawing If you don't close it , Drawing lines will not be closed in the end
ctx.closePath()
// Fill color
ctx.strokeStyle = 'red'
// Draw lines Stroke
ctx.stroke()
// fill Color
ctx.fillStyle = 'orange'
// fill
ctx.fill()

- Draw an arc Demo-3 stroke
let canvas = document.getElementById('cas')
let ctx = canvas.getContext('2d')
ctx.beginPath()
/** * @params1 The center of the circle X coordinate * @params2 The center of the circle Y coordinate * @params3 The radius of the arc * @params4 Starting angle * @params5 Ending angle * @params6 Draw the direction {true Draw counterclockwise false Draw clockwise } * @desc {params4,params5} How the angle is calculated :Math.PI A circle is divided into 6.28 Share (3.14 * 2) That is to say 6.28 A radian 0 Is the horizontal position Math.PI * 2 It's a circle Here's a trick , If params5 - params4 > 6.28 And clockwise Then what you draw must be a circle * */
ctx.arc(300, 300, 100, 0, 3.18, false)
ctx.strokeStyle = 'red'
ctx.stroke()

- The small ball follows the mouse Demo-4 arc
let canvas = document.getElementById('cas')
let ctx = canvas.getContext('2d')
// Clear the current canvas
function clearCanvas() {
ctx.clearRect(0, 0, 600, 600)
}
// Draw a little ball
function drawRound(startX, startY, len, startAngle, endAngle, Directtion, C) {
ctx.beginPath()
ctx.arc(startX, startY, len, startAngle, endAngle, Directtion)
ctx.strokeStyle = C
ctx.stroke()
ctx.fillStyle = C
ctx.fill()
}
// Get the current mouse coordinates With the current canvas The upper left corner of is the vertex
function getMousePosition(event) {
var e = event || window.event;
console.log(e.offsetX, e.offsetY)
clearCanvas()
drawRound(e.offsetX, e.offsetY, 30, 0, Math.PI * 2, false, getRadomColor())
}
// Generate a random color value
function getRadomColor() {
let types = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f']
let color = '#'
for (let i = 0; i < 6; i++) {
let radom = Math.floor(Math.random() * types.length)
color += types[radom]
}
return color
}
// Add a mouse movement event to the current canvas , Update the position of the ball
canvas.addEventListener('mousemove', function (event) {
getMousePosition(event)
})

- Write on the canvas Demo-5 fillText
let canvas = document.getElementById('cas')
let ctx = canvas.getContext('2d')
// What needs to be noticed here :{ If there is no such font here , There will be no show here , That is, his size won't work }
ctx.font = '48px SimSun, Songti SC'
// Add a transparency { Most of them are used to process pictures Here is just an example to deal with a paragraph of text }
ctx.filter = 'opacity(25%)'
//400 Is the width occupied by the font
ctx.fillText("this is canvas",24,66,400)
- Draw a picture on the canvas Demo-6 drawImage
let canvas = document.getElementById('cas')
let ctx = canvas.getContext('2d')
let imgUrl = new Image()
imgUrl.src = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F4k%2Fs%2F02%2F2109242342133248-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1656381685&t=0729cacb65159f78af95f6d9c78bed44'
console.trace(imgUrl)
// The drawing of pictures Must be in onload Draw after , Otherwise, the picture will not be rendered
imgUrl.onload = function (e) {
drawImg(this);
};
// Simple encapsulation of drawing functions
function drawImg(img){
/** * @param1 {String:img} Picture resource address * @param2 {Number:0} Relative to the picture X Point location * @param3 {Number:0} Relative to the picture Y Point location * @param4 {Number:400} The width of the slice * @param5 {Number:267} Cut out height of slice * @param6 {Number:100} Relative to the canvas X Point location * @param7 {Number:100} Relative to the canvas Y Point location * @param8 {Number:140} The width of the slice saved to the canvas * @param9 {Number:110} The height of the slice saved to the canvas * @desc drawImage In the process of drawing Parameters can be 3 individual It can also be 5 individual It can also be 9 individual But at least 3 individual * @params 3 One parameter :{ When there are three parameters , Description: store the picture directly in a certain position on the canvas - img\x\y} * @params 5 One parameter :{ When there are five parameters , Description: store the picture directly to a certain position on the canvas, and specify the width and height of the picture - img\x\y\w\h} */
ctx.drawImage(img,0,0,400,267,100,100,140,110)
}
- Canvas movement and state saving translate、save、restore
let canvas = document.getElementById('cas')
let ctx = canvas.getContext('2d')
// send ctx Move itself to the lower right 50
ctx.translate(50,50)
ctx.fillStyle = "red"
ctx.fillRect(0,0,50,50)
ctx.fillStyle = "blue"
ctx.fillRect(50,50,50,50)

let canvas = document.getElementById('cas')
let ctx = canvas.getContext('2d')
// Save the current without moving ctx Location ( state )
ctx.save()
ctx.translate(50,50)
ctx.fillStyle = "red"
ctx.fillRect(0,0,50,50)
// Restore previously saved ctx The state of
ctx.restore()
ctx.fillStyle = "blue"
ctx.fillRect(50,50,50,50)

- explain
save I thought about it, but I don't know how to describe it to you , That's what the official website says ,“ Save the current Canvas Canvas state and put it on the top of the stack , have access to restore() Methods take out in turn ”restore Generally and save Paired , The aim is to save The saved state is extracted , Of course save and restore Its own role is more than that , There is another sentence in the explanation given on the official website that deserves attention , Save the current Canvas Canvas state and put it on the top of the stack , Note that the stack is used here , That is to say, it conforms to the data structure characteristics of the stack , That is, first in and then out 、 Last in, first out , So I don't know how to demonstrate it here , So I drew a picture that is relatively easy to understand The bottom of the stack is actually the top of the stack , Because I don't want to repeat the drawing , Here's an explanation save Not all attributes can be saved , The attributes he can save are :

- Scaling of canvas attributes scale
There are two reasons for this special explanation , The first is him and css3 Inside scale Different ,canvas There are two parameters, namely XY, however css3 There is only one parameter , Is the overall reduction , Another reason is that Demo Inside
let canvas = document.getElementById('cas')
let ctx = canvas.getContext('2d')
ctx.fillStyle = "red"
ctx.fillRect(50, 50, 50, 50)
ctx.fillStyle = "blue"
ctx.scale(0.5, 0.5)
ctx.fillRect(150, 150, 50, 50)

- canvas Implement export
let canvas = document.getElementById('cas')
let ctx = canvas.getContext('2d')
ctx.beginPath()
ctx.fillStyle = 'red'
ctx.arc(100, 100, 50, 0, 2 * Math.PI, false)
ctx.fill()
// export base64 file
// let data = canvas.toDataURL('image/jpeg', 1)
// console.log(data)
// export Blob file
let data = canvas.toBlob((v) => {
console.log(v)
}, 'image/jpeg', 0.7)
Run it by yourself ! There is no special explanation !
- Implement a scaled circle
let canvas = document.getElementById('cas')
let ctx = canvas.getContext('2d')
let r = 10
let stopFlag = setInterval(() => {
r++
drawArc(r)
if (r > 50) {
let f = setInterval(() => {
r--
drawArc(r)
if (r < 10) {
clearInterval(f)
}
}, 10)
}
}, 20)
// Draw a circle
function drawArc(r) {
ctx.beginPath()
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.strokeStyle = 'red'
ctx.filter = 'drop-shadow(4px 4px 8px red)'
ctx.arc(canvas.width / 2, canvas.height / 2, r, 0, 2 * Math.PI, false)
ctx.stroke()
ctx.closePath()
}
- Realize a small game
<!-- * @use: Run directly to html that will do * @description: To produce a random number To judge whether or not you win the prize * @SpecialInstructions: nothing * @Author: clearlove * @Date: 2022-05-28 17:55:04 * @LastEditTime: 2022-05-30 00:04:05 * @FilePath: /universal-background-template/Users/leimingwei/Desktop/ Open source code /canvas/ Click the mouse and a colorful ball will appear .html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Click on the draw </title>
<style> button {
margin-bottom: 40px; width: 150px; height: 50px; border-radius: 5px; background-color: burlywood; font-size: 24px; color: #fff; border: none; cursor: pointer; } .result {
width: 200px; height: 60px; position: relative; user-select: none; } input {
width: 200px; height: 60px; font-size: 30px; line-height: 60px; text-align: center; position: absolute; user-select: none; border: none; top: 0; left: 0; } canvas {
position: absolute; top: 0; left: 0; } </style>
</head>
<body>
<button onclick="beginGame()"> Start the lottery </button>
<div class="result">
<input disabled id="result" value=" I won the prize ">
<canvas id="cas" width="200" height="60"></canvas>
</div>
</body>
<script> function beginGame() {
// Refresh the page Reset game location.reload() } // Start the game function startGame() {
// Save random results let result = document.getElementById('result') result.value = readomRasult() let canvas = document.getElementById('cas') let ctx = canvas.getContext('2d') // Draw a rectangle ctx.fillStyle = '#ccc' ctx.fillRect(0, 0, 200, 60) // Clear the post generated elements ctx.globalCompositeOperation = 'destination-out' // Add an event , Press the mouse down and slide canvas.onmousedown = () => {
canvas.onmousemove = (event) => {
ctx.beginPath() ctx.arc(event.offsetX, event.offsetY, 10, 0, 2 * Math.PI, false) ctx.fill() } } } // Generate random winning results The conditions here can be changed by yourself , Improve the winning rate function readomRasult() {
let res = "" let n = Math.floor(Math.random() * 100) if (n % 3 === 0) {
res = " I won the prize " } else {
res = " unfortunately " } return res } startGame() </script>
</html>

Wrote last
This article is a bit long , I feel it myself , however canvas I was going to write every attribute , Or write a demo demonstrate , But I thought about , This method has no practical significance , Because the examples given on the official website are already very detailed , So the way I think of is to implement some relatively simple properties according to some common attribute methods demo effect , In this way, you can practice to canvas The attribute part of , It can also improve our understanding of canvas The pleasure of , Many of the examples above are B The station appeared, and I wrote it myself , because B The example above is representative , I hope the above examples can help us understand canvas Better understand , It's a long story , I believe everything here is right canvas Want to learn , I'm not quite right myself canvas I know very well , I am also in the process of learning , So the above examples or explanations are not guaranteed to be completely correct , I can only say that the effect is the above effect when I run , The other thing is that the article just canvas The basic usage of , Some complex applications , We need to combine according to the basic method , I hope you can correct any mistakes in time !
边栏推荐
- MySQL创建给出语句
- Remittance international empowers cross-border e-commerce: to be a compliant cross-border payment platform!
- Webapi performance optimization
- Gradle download warehouse is slow
- How do wechat applets make their own programs? How to make small programs on wechat?
- tokenizers>=0.11.1,!=0.11.3,<0.13 is required for a normal functioning of this module,
- How to make a self-service order wechat applet? How to do the wechat order applet? visual editing
- CyCa children's physical etiquette Yueqing City training results assessment successfully concluded
- Jetpack compose layout (IV) - constraintlayout
- Shuttle JSON, list, map inter transfer
猜你喜欢

链表 删除链表中的节点

Wearable devices may reveal personal privacy
![[MySQL learning notes 21] storage engine](/img/3a/a3cd573281efc689cafdb7d7562ce0.png)
[MySQL learning notes 21] storage engine

MongoDB的原理、基本使用、集群和分片集群

Can two Mitsubishi PLC adopt bcnettcp protocol to realize wireless communication of network interface?

Minio基本使用与原理

Jetpack compose layout (I) - basic knowledge of layout

Jetpack compose layout (IV) - constraintlayout

i++ 和 ++i的真正区别

Modbus protocol and serialport port read / write
随机推荐
i++ 和 ++i的真正区别
Gradle download warehouse is slow
Puzzle (019.2) hexagonal lock
Flutter Gaode map privacy compliance error
ShardingSphere-Proxy 4.1 分库分表
WPF 绑定表达式和绑定数据源(一)
Principle of distribution: understanding the gossip protocol
Set the location permission in the shutter to "always allow"
Mysql 源码阅读(二)登录连接调试
力扣-104. 二叉树的最大深度
[buuctf.reverse] 121-125
Guiding principle - read source code
An auxiliary MVP architecture project quick development library -mvpfastdagger
manhattan_ Slam environment configuration
tokenizers>=0.11.1,!=0.11.3,<0.13 is required for a normal functioning of this module,
Etcd tutorial - Chapter 4 etcd cluster security configuration
View. post VS Handler. Differences and usage scenarios of post
Processing picture class library
How much does a small program cost? How much does a small program cost? It's clear at a glance
Solutions using protobuf in TS projects
