1.掌握绘制矩形的方法:strkeRect()/fillRect()
2.掌握绘制路径的beginPath()和closePath()
beginPath()用来创建新的路径
closePath()从当前点回到起始点,封闭路径 边角无漏
context3.moveTo(100,100);
context3.lineTo(400,100);
context3.lineTo(400,400);
context3.lineTo(100,400);
//context3.lineTo(100,100);
context3.closePath();
context3.stroke();
3.rect(x,y,w,h)创建一个矩形,strokeRect(x,y,w,hx,y,w,h)绘制矩形(无填充)
strokeRect(x,y,w,h)相当于Rect(x,y,w,h)+stroke()
<script type="text/javascript">
var canvas3=document.getElementById(‘mycanvas3‘);
var context3=canvas3.getContext(‘2d‘);
context3.lineWidth=10;
context3.strokeStyle="#A52A2A";
context3.rect(200,200,100,100);
context3.stroke();
var c=canvas3.getContext(‘2d‘);
c.beginPath();
c.lineWidth=10;
c.strokeStyle=‘green‘;
c.strokeRect(100,100,100,100);
</script>
4.fillRect(x,y,w,h)绘制“被填充”的矩形,fill()绘制已定义的路径(带填充的图形)
var c=canvas3.getContext(‘2d‘);
c.beginPath();
c.lineWidth=10;
c.strokeStyle=‘green‘;
c.strokeRect(100,100,100,100);
c.beginPath();
c.fillStyle=‘red‘;
c.rect(300,100,100,100);
c.fill();
c.beginPath();
c.fillStyle=‘black‘;
c.fillRect(100,300,100,100);
c.fillRect(300,300,100,100);
5.stroke()绘制已定义的路径
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas绘制矩形</title>
<style type="text/css">
canvas{background:#000fff}
</style>
</head>
<body>
<canvas id="mycanvas3" width="500" height="500">
</canvas>
<script type="text/javascript">
var canvas3=document.getElementById(‘mycanvas3‘);
var context3=canvas3.getContext(‘2d‘);
context3.lineWidth=10;
context3.strokeStyle="#A52A2A";
context3.moveTo(100,100);
context3.lineTo(400,100);
context3.lineTo(400,400);
context3.lineTo(100,400);
//context3.lineTo(100,100);
context3.closePath();
context3.stroke();
context3.beginPath();
context3.lineWidth=5;
context3.strokeStyle="green";
context3.rect(200,200,100,100);
context3.stroke();
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas绘制矩形</title>
<style type="text/css">
canvas{background:#000fff}
</style>
</head>
<body>
<canvas id="mycanvas3" width="500" height="500">
</canvas>
<script type="text/javascript">
var canvas3=document.getElementById(‘mycanvas3‘);
var context3=canvas3.getContext(‘2d‘);
context3.lineWidth=10;
context3.strokeStyle="#A52A2A";
context3.rect(200,200,100,100);
context3.stroke();
var c=canvas3.getContext(‘2d‘);
c.beginPath();
c.lineWidth=10;
c.strokeStyle=‘green‘;
c.strokeRect(100,100,100,100);
c.beginPath();
c.fillStyle=‘red‘;
c.rect(300,100,100,100);
c.fill();
c.beginPath();
c.fillStyle=‘black‘;
c.fillRect(100,300,100,100);
c.fillRect(300,300,100,100);
</script>
</body>
</html>
原文:http://www.cnblogs.com/liao13160678112/p/6394929.html