canvas绘图是基于状态的绘图方式

 1 window.onload = function() {
 2 
 3     var canvas = document.getElementById("canvas");
 4 
 5     canvas.width = 1024;
 6     canvas.height = 768;
 7 
 8     var context = canvas.getContext("2d");
 9 
10     context.beginPath();
11     context.moveTo(100,100);
12     context.lineTo(700,700);
13     context.lineTo(100,700);
14 
15     context.closePath();    //自动闭合路径
16 
17     context.lineWidth = 5;
18     context.strokeStyle = "red";
19     context.stroke();
20 
21     context.beginPath();
22     context.moveTo(200,100);
23     context.lineTo(700,600);
24     context.closePath();
25     context.strokeStyle = "black";
26     context.stroke();
27     //每使用一次stroke(),就将之前的状态绘制一遍
28 
29     //使用context绘制
30 
31 };

ps:http://www.w3schools.com/tags/canvas_stroke.asp中对stroke()的解释:

The stroke() method actually draws the path you have defined with all those moveTo() and lineTo() methods.

原文地址:https://www.cnblogs.com/csuhyd/p/4367062.html