在使用<canvas>元素之前,首先要检测getContext()方法是否存在。
var drawing=document.getElementById('drawing');
if(drawing.getContext){
var context=drawing.getContext("2d");
}
1.基本操作:填充和描边
填充:context.fillStyle="pink";
描边:context.strokeStyle="blue";
2.绘制矩形
//绘制矩形
context.fillStyle="pink";//填充色
context.fillRect(10,10,60,60); //绘制具有填充色的矩形,参数为:矩形左上角的x,y坐标,矩形的宽度和高度
context.strokeStyle="blue";//边框色
context.strokeRect(80,10,60,60);//绘制具有描边的矩形
context.clearRect(20,20,10,10);//clearRect()方法用于清除画布上的某块矩形区域
在绘制一个边长为60的正方形时,发现绘制出来的形状为长方形,解决方法:不要再CSS中定义Canvas的长宽,需要再代码中直接写入长宽。
3.绘制路径
调用beginPath()方法,表示要开始绘制新路径,再调用lineTo()等方法来实际绘制路径。
若要绘制一条连接到起点的线条,调用closePath()方法。调用fill()方法可填充颜色,调用stroke()方法对路径描边。
//绘制路径
//绘制一条直线
context.strokeStyle="#669933";
context.lineWidth=10;//线条宽度
context.lineCap="round";//线条末端的形状,butt平头,round圆头,square方头
context.moveTo(200,20);//moveTo(x,y)将绘图游标移动到(x,y),不画线
context.lineTo(350,20);//lineTo(x,y)从上一点开始绘制一条直线,到(x,y)为止
context.lineTo(360,40);
context.stroke();//描边路径
//绘制一个圆
context.beginPath();
context.arc(250,60,20,0,Math.PI*2,true);//以(250,60)为圆心,20为半径,起始和结束角度为0和2PI,true表示逆时针,false为顺时针
context.closePath();
context.fillStyle="yellow";
context.fill();
4.绘制文本
//绘制文本
context.font="bold 20px Arial";//文本样式
context.textAlign="start";//文本对齐方式,有center文本中心,start文本左端,end文本右端
context.textBaseline="middle";//文本基线
context.fillStyle="orange";
context.fillText("Good morning",50,100);