Canvas Basic Tutorial (Chapter 1)

  This is my first Canvas basic tutorial. Let me briefly describe what Canvas is.
  The new content of H5 allows scripting language to dynamically render images. It is a drawable area defined by HTML code with height and width attributes. JavaScript code can access this area, similar to other general two-dimensional APIs, and dynamically generate graphics through a complete set of drawing functions. Some possible uses include using Canvas to construct graphics, animations, games and pictures.

The property of the Canvas object
height property:
  the height of the canvas. Like an image, this attribute can be specified as an integer pixel value or a percentage of the window height. When this value is changed, any drawing that has been done on the canvas will be erased. The default value is 150.

width attribute:
  the width of the canvas. Like an image, this attribute can be specified as an integer pixel value or a percentage of the window width. When this value is changed, any drawing that has been done on the canvas will be erased. The default value is 300.


What are the advantages of graphics or animation drawn by Canvas?

比如下面这张图:
Insert picture description here
  Regardless of the video, even if it is a gif, such an uncompressed picture, the size is at least 4MB. When the browser renders this picture, it is equivalent to downloading a "smooth" quality song. If you want this If a picture is used as a background picture, it will become very blurry.

  What if it is a Canvas? Its size is only 2KB, even if you are on a 2G network, it can be loaded quickly and can withstand unlimited enlargement. The only disadvantage is that you only need to pull up the picture, while Canvas has to write 100 lines of code.


The production principle of Canvas animation
  1. Update drawn objects (such as position movement)
  2. Clear the canvas
  3. Redraw objects on the canvas. A
  simple summary: continuous drawing and removal.


The beginning of the tutorial:
  adding Canvas to HTML is very simple, just add the <canvas> tag in the <body>! Tags usually need to specify an id attribute (often quoted in scripts), the size of the canvas defined by the width and height attributes. You can refer to the following code.

<body>
    <canvas id="canvas" width="200" height="100">一张Canvas 画布</canvas>
</body> 

Get the canvas

var c=document.getElementById(“canvas”);
var ctx=c.getContext(“2d”);

  These two pieces of code are required. This is a template. From the early stage, no matter what you draw, it will not change. I won't go into details here and it is not easy to understand.

Canvas-text

font-defines the font
fillText(text,x,y)
-draws solid text on the canvas strokeText(text,x,y)-draws hollow text on the canvas

Canvas-Image

drawImage(image,x,y)

Canvas color

ctx.fillStyle = " "

Canvas coordinates

Canvas is a two-dimensional grid.
The coordinates of the upper left corner of the canvas are (0,0).
The X coordinate increases to the right.
The Y coordinate increases toward the bottom of the canvas.

Insert picture description hereCanvas-path

moveTo(x,y) defines the start coordinates of the line
lineTo(x,y) defines the end coordinates of the line

If you draw a circle in the canvas, you can use arc(x,y,r,start,stop)

Canvas-gradient

createLinearGradient(x,y,x1,y1)
-create a line gradient createRadialGradient(x,y,r,x1,y1,r1)-create a radial/circular gradient

Use of canvas

ctx.font=“bold 20px Arial”;
ctx.textAlign=“Hello W3Cschool”;
ctx.fillText(“Hello W3Cschool”, 20, 40);

In canvas, the transform property still takes effect, but it is abbreviated as: ctx.translate(x,y), ctx.rotate(x), etc.

It should be noted that: the rotateangle can no longer be filled in, it should be changed to:

ctx.rotate((Math.PI / 180) * 25)

Means: rotate 25 deg clockwise

Let's write a simple small case to see how it works:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>

</head>
<body>
	<canvas id="canvas"  width="500" height="500"></canvas>
<script>
    var c=document.getElementById("canvas");
	var ctx=c.getContext("2d");
	ctx.translate(100, 150);
	ctx.fillText("after translate", 20, 40);
	ctx.fillStyle = "gray";
	ctx.fillRect(10,10, 100, 100);
	ctx.rotate( (Math.PI / 180) * 25);
	ctx.fillStyle = "orange";
	ctx.fillRect(10,10, 100, 100);
</script>
</body>
</html>

Insert picture description here  The most amazing thing about Canvas is that it keeps adding. When you draw a good graph, let it clone itself frequently, so you get N drawn graphs. This is also the principle of the initial animation. Such as:

<body>
	<canvas id="canvas"  width="500" height="500"></canvas>
<script>
    var c=document.getElementById("canvas");
	var ctx=c.getContext("2d");
	ctx.strokeRect(10,10,30,20);
	ctx.scale(2,2);
	ctx.strokeRect(10,10,30,20);
	ctx.scale(2,2);
	ctx.strokeRect(10,10,30,20);
	ctx.scale(2,2);
	ctx.strokeRect(10,10,30,20);
</script>

Effect picture:

Insert picture description hereThen we use what we just learned to do a small exercise:

<body>
    <canvas id="canvas"  width="500" height="500">
    <script>
        var testCanvas = document.getElementById("canvas");
        // 获取getContext()对象
        var context = testCanvas.getContext("2d");
 
        context.fillStyle = "red";
        context.fillRect(10, 10, 100, 100);
        // 保存状态(红色)
        context.save();
 
        context.fillStyle="blue";
        context.fillRect(60, 60, 100, 100);
        // 保存状态(蓝色)
        context.save();
 
        // 恢复状态(红色)
        context.restore();
        context.fillRect(120, 120, 100, 100);
 
        // 恢复状态(蓝色)
        context.restore();
        context.fillRect(180, 180, 100, 100);
        context.beginPath();
    </script>
</body>

  See if the pattern you get is as follows: After
Insert picture description here
  reading this, do you want to ask, how are those moving canvas animations made?

<style>
	.onfo {
     
     
		width: 600px;
		height: 400px;       
	}
	.onfo canvas {
     
     
		border: 1px solid #333;
	}
</style>
</head>
<body>
    <div class="onfo">
        <canvas id="canvas"  width="500" height="500">  
    </div>
<script>
    var testCanvas = document.getElementById("canvas");
    var context = testCanvas.getContext("2d");
    var x = 0;
    var y = 0;
    var timer = null;

    //清除画布 再次绘制(循环操作)
    function draw(){
     
     
        // 不断改变绘制对象的水平位置
        x++;
        // 清除画布
        context.clearRect(0, 0, 600, 400);
        context.beginPath();
        context.fillStyle = "skyblue";
        context.arc(x, 200, 80, 0, 2 * Math.PI, true);
        context.closePath();
        // 绘制轮廓
        context.stroke();
        // 填充颜色
        context.fill();
    }
    
    // 设置计时器
    setInterval(draw, 20);
</script>
</body>

  Let’s take a look at the renderings. Is it the same as mine?
Insert picture description here
  The Canvas tutorial of this issue is over here. This technology will shine in future development and installation of X. Diligent study and practice will make us perfect. Bo Ba Lao Tie Insert picture description herefinally gave you three advanced and simple Canvas animations, which can both practice and install X. I am "I am not Fei Yuan", a person who is busy with codewords every day until late at night. I never give up easily. Never skimp on his own words of praise. If you have higher attainments on canvas, I hope to get your advice. On the contrary, I hope you can go hand in hand with me.

Recommended reading:
Line animation,
line garland,
heartbeat

Guess you like

Origin blog.csdn.net/weixin_45820444/article/details/108905028