1、canvas 导入
HTML:
<canvas id=“canvas”>你的浏览器不支持canvas,请更换浏览器</canvas>
js:
var canvas = document.getElementById(‘canvas’);
var ctx=canvas.getContext(‘2d’);
canvas.height=…
canvas.width=…
2、常用属性
- ctx.beginePath ; //开辟一个新路径(新状态)
- ctx.moveTo(200,300); //画笔移动到(200,300)位置
- ctx.lineTo(299,300); //从画笔的位置画一条直线到(299,300)位置
- ctx.strokeStyle=“red”; //描边的颜色设置为红色
- ctx.lineWidth= 5 ; //画笔的宽度5px
- ctx.stroke() ; //描边
- ctx.closePath() ; //闭合路径
- ctx.fillStyle=‘green’; //填充的颜色为green
- ctx.fill() ; //填充颜色 默认为黑色
3、矩形绘制
ctx.rect(30,44,200,300); //在(30,44)位置绘制200300的空心矩形
ctx.stroke();
ctx.strokeRect(30,44,200,300); //在(30,44)位置绘制200300空心的矩形
ctx.fillRect(30,44,200,300); //在(30,44)位置绘制200*300实心的矩形
ctx.clearRect(30,44,200,300); //清除矩形
4、绘制弧
ctx.arc(x,y,r,初始角,结束角,是否逆时针绘制) //初始、终止角为与x轴的夹角(顺时针0-2PI)
如:
ctx.arc(20,50,100,30Math.PI/180,0Math.PI/180,false); //在(20,50)位置绘制半径为100px 起始角度为30弧度,终止弧度为0弧度,ture–>逆时针绘制,false为顺时针
5、文字
ctx.strokeText(“所要绘制的文字”,x,y); //绘制只有描边的文字
ctx.fillText(“所要绘制的文字”,x,y); //绘制填充的文字
ctx.font=“20px 微软雅黑” ; //字体大小为20px 字体样式为 Arial
ctx.textBaseline=“bottom”; //对齐基线为bottom 即底线与。。。对齐 top middle
ctx.textAlign=“left”; //对齐方式 left right end start center
var b= ctx.measure(“你还好吗”); //返回文本宽度( “你还好吗” 的宽度 )
ctx.shadowColor=“teal” // 填充的阴影颜色 (蓝绿色)
ctx.shadowBlur=1-1000000 //…
ctx.shadowOffsetX=10; // 阴影的偏移量
ctx.shadowOffsetY=10;
6、渐变
- 线性渐变
var grad=ctx.createLinearGradient(x1,y1,x2,y2);
//创建一个线性渐变( 冲x1,y1====》x2,y2 )
grad.addColorStop(0,“red” ); //0~1表示渐变的位置
grad.addColorStop(.5,“white”);
grad.addColorStop(1,“cyan”);
ctx.fillStyle=grad; //从red渐变到white再渐变到cyan;
- 渐变
var rly= ctx.createRadialGradient(300,300,10,300,100);
//创建圆形渐变
rly.addColorStop(0,“red” );
rly.addColorStop(.7,“white”);
rly.addColorStop(1,“cyan”);
ctx.fillStyle=rlg;
ctx.fillRect(100,100,500,500);
7、图片绘制
var img=new Image();
img.src="…";
img.οnlοad=function(){…}
ctx.drawImage(img,x,y,width,height); //img为创建的Image对象;x,y为画布的坐标 width ,height 原来设置插入图片的长度和宽度;
ctx.drawImage(img,sx,sy,swidth,sheight,x,y,width,height); //剪切图像-- sx,sy 为图片的始点 swidthwe,sheight为被修剪的长和宽
//配合setInterval ()、clearRect()可制作帧动画
8、canvas坐标变化
ctx.save(); //保存当前画布、使变化前面的元素不受影响
ctx.translate( 200,200); //移动画布到200,200位置
ctx.rotate(30*Math.PI/180); //将画布顺时针旋转30度
ctx.scale(2,2); //将画布x ,y分别放大2被
ctx.globalAlpha=0.3 ; //将画布透明化 30%
ctx.restore(); //返回保存过的画布