第一步:html5页面中添加canvas元素
1
|
<
canvas
id
=
"mycanvas"
width
=
"300"
height
=
"300"
></
canvas
id
=
"mycanvas"
width
=
"300"
height
=
"300"
>
|
1、javascript绘制图形(矩形)
1
2
3
4
5
6
|
<
script
type
=
"text javascript"
="">
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d"); //获取允许绘制图像的2D环境
cxt.fillStyle="#FF0000"; //fillStyle为绘制的图像填充颜色
cxt.fillRect(0,0,150,75); //fillRect绘制矩形,前两个坐标为x,y轴,后面为宽高
</
script
type="text>
|
除了可以使用fillStyle和fillRect,还可以使用strokeStyle和strokeRect,fill是填充,而stroke是轮廓,所有用strokeStyle和strokeRect是绘制的矩形轮廓,而fillStyle与fillRect绘制的是实体矩形。
2、绘制直线(使用 moveTo、lineTo、stroke方法)
moveTo(x,y):用于建立新的子路径,规定起始点为 (x,y)
lineTo(x,y):用于从moveTo方法规定的起始点开始绘制一条到规定坐标的直线。
stroke():用于沿着该路径绘制一条直接。
1
2
3
4
5
6
7
8
9
10
|
<script type=
"text javascript"
=
""
>
window.onload =
function
(){
var
c = document.getElementById(
'myCanvas'
);
var
content = c.getContext(
'2d'
);
content.moveTo(0,0);
content.lineTo(300,300);
content.stroke();
};
</script type="text>
|
3、绘制圆形(用到beginPath、arc、closePath、fill这四个方法)
beginPath():用于开始绘制路径
closePath():用于将图形闭合起来
arc(x,y,radius,startAngle,endAngle,anticlockwise):用于绘制圆形,x,y为坐标,radius为半径,startAngle为开始的角度,endAngle为结束的半径,anticlockwise为是否按顺时针方向绘制图形。
1
2
3
4
5
6
7
8
9
10
11
12
|
<script type=
"text javascript"
=
""
>
window.onload =
function
(){
var
c = document.getElementById(
'myCanvas'
);
var
content = c.getContext(
'2d'
);
content.fillStyle=
"#FA7E2A"
;
content.beginPath();
content.arc(50,50,50,0,Math.PI*2,
true
);
content.closePath();
content.fill();
};
</script type="text>
|
4、绘制三角形
清除:clearRect(x,y,width,height); x,y为坐标
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
31
|
<
meta
charset
=
"utf-8"
>
<
title
></
title
>
<
style
type
=
"text css"
="">
*{padding: 0;margin:0;}
#div1{margin:50px auto; width:300px; height: 300px;}
canvas{border:1px solid #000;}
<
script
type
=
"text javascript"
="">
window.onload = function(){
var c = document.getElementById('myCanvas');
var content = c.getContext('2d');
content.fillStyle = '#FA7E2A';
content.beginPath();
content.moveTo(25,25);
content.lineTo(150,25);
content.lineTo(25,150);
content.closePath();
content.fill();
document.getElementsByTagName('input')[0].onclick = function(){
content.clearRect(0,0,300,300);
};
};
<
div
id
=
"div1"
>
<
canvas
id
=
"mycanvas"
width
=
"300"
height
=
"300"
>
<
input
type
=
"button"
value
=
"清除画布"
>
</
input
type
=
"button"
value
=
"清除画布"
></
canvas
id
=
"mycanvas"
width
=
"300"
height
=
"300"
></
div
id
=
"div1"
></
script
type="text></
style
type="text></
meta
charset
=
"utf-8"
>
|