canvas基础

canvas基础



1.获取上下文

var canvas=document.getElementById('canvas1');
//getContext中有一个参数需要填写。目前只有一个值2d,暂时不支持3d,未来可能加入3d;
var context = canvas.getContext('2d');

2.绘图

三角形
context.strokeStyle = "red";
context.lineWidth = 10;
//注意:在绘制之前先要开始路径。
context.beginPath();  //(绘制新的图形之前)
context.moveTo(10,10);
context.lineTo(10,100);
context.lineTo(100,100);
context.lineTo(10,10);
context.closePath();  //(只有需要封闭结尾的时候才用)
context.stroke();    

绘制矩形(带边框)
context.fillStyle = "red";  //(颜色要放在前面)
context.rect(100,100,200,100);  //(x,y,w,h)
context.stroke();    //(画线段)
context.fill();

只有填充颜色的矩形
context.beginPath();
context.fillStyle = "red";
context.fillRect(120,120,200,100);

绘制弧线
context.moveTo(400,300)
context.arc(300,300,100,0,Math.PI/2,false); //(x,y,r,0,PI,false)false代表顺时针
context.stroke();

绘制实心圆
context.fillStyle = "red";
context.moveTo(400,300)
context.arc(300,300,100,0,Math.PI*2,false);
context.stroke();
context.fill();

绘制文字
context.beginPath();
context.font="30px Arial";
context.strokeText("lanou3g",50,50);

渐变
var linearGradient = context.createLinearGradient(50,50,170,50);
linearGradient.addColorStop(0,"red");
linearGradient.addColorStop(0.5,"yellow");
linearGradient.addColorStop(1,"green");
context.strokeStyle=linearGradient;
context.beginPath();
context.font="30px Arial";
context.strokeText("lanou3g",50,50);