先创建canvas标签
<canvas id="myCanvas" width="800" height="500" style="background:#eee">
Your browser does not support HTML5 Canvas.
</canvas>
然后写js代码。可放在<script></script>标签里边,也可以放在外部js文件里边。
首先获取canvas:
var myCanvas = document.getElementById('myCanvas');
var ctx = myCanvas.getContext('2d');
//可用一句代码表示:var ctx = document.getElementById('myCanvas').getContext('2d');
然后就可以进行各种操作了
基础方法:
1.ctx.fillStyle = '颜色'; //设置或返回用于填充绘画的颜色、渐变或模式
2.ctx.strokeStyle = ''; //设置或返回用于笔触的颜色、渐变或模式
3.ctx.shadowStyle = ''; //设置或返回用于阴影的颜色
4.ctx.shadowBlur = ''; //设置或返回用于阴影的模糊级别
5.ctx.shadowOffsetX = ''; //设置或返回阴影距形状的水平距离
6.ctx.shadowOffsetY = ''; //设置或返回阴影距形状的垂直距离
1.画线
ctx.beginPath(0,0); //起点 (x,y) 以(0,0)点为原点,x为x轴,y为y轴。
ctx.moveTo(0,0); //把路径移动到画布中的指定点,不创建线条。
ctx.lineTo(100,100); //终点
ctx.lineTo(300,400); //连续画线,以上一个终点为起点
2.画矩形
ctx.fillRect(x,y,width,height); //此方法画出来的是填充的矩形,默认颜色为#000,要是想要改变填充颜色,则需要将ctx.fillStyle = '颜色';放到其前面
ctx.strokeRect(x,y,width,height); ///此方法画出来的是非填充的矩形,默认颜色为#000,要是想要改变填充颜色,则需要将ctx.fillStyle = '颜色';放到其前面
3.画圆
ctx.arc(x,y,r,起始角度,结束角度); //此方法画空心圆
4.渐变
//创建渐变
var grd=ctx.createLinearGradient(0,20,200,30);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
//填充渐变
ctx.fillStyle=grd;
ctx.fillRect(20,400,150,80);
//创建渐变
var grd=ctx.createRadialGradient(550,250,5,550,250,150);
grd.addColorStop(0,"red");
grd.addColorStop(1,"#ffffaa");
//填充渐变
ctx.fillStyle=grd;
ctx.fillRect(400,100,300,300);