使用Canvas绘制图形&贝塞尔曲线


绘制图形

实例1:绘制直线

1
2
3
4
5
6
7
8
9
10
11
<canvas id="aaa" width="300" height="300" style="border: 1px solid blue;">
</canvas>
<script>
var a=document.getElementById('aaa');
var cx=a.getContext('2d');
cx.moveTo(0,0);
cx.lineTo(300,300);
cx.strokeStyle='green';
cx.lineWidth=5;
cx.stroke();//放在后边
</script>

实例2:绘制三角形

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<canvas id="bbb" width="300" height="300" style="border: 1px solid blue;">
</canvas>
<script>
var b=document.getElementById('bbb');
var cxz=b.getContext('2d');
//开始于结束路径,防止多个图形粘连
cxz.beginPath();
cxz.moveTo(100,50);
cxz.lineTo(50,250);
cxz.lineTo(200,250);
// cxz.lineTo(100,50);使用了开始结束路径,就可以删除最后的连接
cxz.closePath();
cxz.strokeStyle='green';
cxz.lineWidth=5;
cxz.fillStyle='yellow';
cxz.fill();
cxz.stroke();
//第二个三角形
cxz.beginPath();
cxz.moveTo(200,50);
cxz.lineTo(250,50);
cxz.lineTo(200,200);
// cxz.lineTo(200,50);
cxz.closePath();
cxz.strokeStyle='pink';
cxz.lineWidth=5;
cxz.fillStyle='red';
cxz.fill();
cxz.stroke();
</script>

实例3:绘制矩形

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<canvas id="ccc" width="300" height="300" style="border: 1px solid blue;">
</canvas>
<script>
var c=document.getElementById('ccc');
var cxt=c.getContext('2d');
//第一种
// cxt.rect(50,100,200,100);
// cxt.strokeStyle='blue';
// cxt.fillStyle='yellow';
// cxt.fill();
// cxt.stroke();
// cxt.strokeRect(50,100,200,100);//快速绘制矩形
cxt.fillStyle='yellow';//得放在之前
cxt.fillRect(50,100,200,100);//带有填充色的矩形
cxt.clearRect(70,120,80,50);//清除画布
</script>

实例4:绘制圆形

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<canvas id="ddd" width="300" height="300" style="border: 1px solid blue;">
</canvas>
<script>
var d=document.getElementById('ddd');
var cxs=d.getContext('2d');
cxs.beginPath();
cxs.arc(150,100,100,0,Math.PI*2,true);
cxs.closePath();
cxs.fillStyle='pink';
cxs.fill();
cxs.beginPath();
cxs.arc(240,240,50,0,Math.PI/2,false);
cxs.closePath();
cxs.fillStyle='#ff8822';
cxs.fill();
</script>

贝塞尔曲线

贝塞尔曲线实例网站地址:
二次贝塞尔曲线:http://blogs.sitepointstatic.com/examples/tech/canvas-curves/quadratic-curve.html
三次贝塞尔曲线:http://blogs.sitepointstatic.com/examples/tech/canvas-curves/bezier-curve.html


文章作者: COOL
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 COOL !
评论
  目录