canvas画布:
(1)方法:获取画布,var canvas=document.getElementById("");
获取上下文对象 (获取画笔),var cx=canvas.getContext(“2d”);
设置画笔样式:cx.fillStyle=‘red’;
cx.strokeStyle=‘blue’;
开始绘制
(2)矩形:fillRect(x,y,w,h);:实心填充元素
strokeRect(x,y,w,h);:描边
圆形:cx.beginPath();
cx.arc(x,y,r,begin,end,c);//设置圆
cx.closePath();
cx.fill();//实心填充
cx.stroke();//描边
线段:moveTo(x,y):x,y:线段的起点坐标
lineTo(x,y):x,y:线段的终点坐标
cx.stroke();//fill():不能使用
lineWidth=number;
渐变:线性渐变:var g=createLinearGradient(bx,by,ex,ey):
g.addColorStop(offset,color);
cx.fillStyle=g;
圆形渐变(径向):createRadialGradient(bx,by,br,ex,ey,er);
变形:平移
扩大
旋转
保存和回滚
圆形组合:globalCompositeOperation=type;
绘制文本:cx.font=‘16px blod’;
fillText(str,x,y,px);
strokeText(str,x,y,px);
例子:画一个表
html部分
<canvas id="canvas" width="600px" height="600px" style="background-color: rgba(233, 150, 122, 0.226);"></canvas>
js部分
window.οnlοad=function(){
var canvas=document.getElementById("canvas");
var cx=canvas.getContext("2d");
function clock(){
cx.fillStyle="pink";
cx.beginPath();
cx.arc(300,300,200,0,Math.PI*2);
cx.closePath();
cx.fill();
cx.strokeStyle="burlywood";
cx.lineWidth=5
cx.beginPath();
cx.arc(300,300,250,0,Math.PI*2);
cx.closePath();
cx.stroke();
//绘制刻度
cx.lineWidth=2;
cx.strokeStyle="black";
for(var i=0;i<12;i++){
cx.save();
cx.translate(300,300);
cx.rotate(i*(Math.PI/6));
cx.beginPath();
cx.moveTo(0,-180);
cx.lineTo(0,-200);
cx.closePath();
cx.stroke();
cx.fillStyle="black";
cx.font="16px blod";
cx.rotate(Math.PI/6);
cx.fillText(i+1,-5,-220);//刻度数字
cx.restore();
}
//分刻度
for(var i=0;i<=60;i++){
cx.save();
cx.beginPath();
cx.translate(300,300);
cx.rotate(i*(Math.PI/30));
cx.moveTo(0,-190);
cx.lineTo(0,-200);
cx.stroke();
cx.closePath();
cx.restore();
}
//获取当前时间
var today=new Date();
var hour=today.getHours();
var min=today.getMinutes();
var sec=today.getSeconds();
hour=hour+min/60;
//时针
cx.lineWidth=5
cx.save();
cx.translate(300,300);
cx.rotate(hour*(Math.PI/6));
cx.beginPath();
cx.moveTo(0,10);
cx.lineTo(0,-120);
cx.closePath();
cx.stroke();
cx.restore();
//分针
cx.lineWidth=3;
cx.save();
cx.translate(300,300);
cx.rotate(min*(Math.PI/30));
cx.beginPath();
cx.moveTo(0,10);
cx.lineTo(0,-160);
cx.closePath();
cx.stroke();
cx.restore();
//秒针
cx.lineWidth=1;
cx.strokeStyle="purple";
cx.save();
cx.translate(300,300);
cx.rotate(sec*(Math.PI/30));
cx.beginPath();
cx.moveTo(0,10);
cx.lineTo(0,-180);
cx.closePath();
cx.stroke();
cx.restore();
//交叉处
cx.fillStyle="white";
cx.strokeStyle="black";
cx.save();
cx.translate(300,300);
cx.beginPath();
cx.arc(0,0,5,0,Math.PI*2);
cx.closePath();
cx.fill();
cx.stroke();
cx.restore();
setTimeout(clock,1000);
}
clock();
}