
正文
Canvas学习
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
参考了慕课网课程:炫丽的倒计时效果Canvas绘图与动画基础
感谢 liuyubobobo 老师 ,提供了这么好的课程
1、<canvas><canvas>标签
注意:最好在标签中指定canvas的width 和 height 或者用js : canvas.width , canvas.height
<canvas>如果你的浏览器支持canvas,那么你将看不到这行文字</canvas>
注意:canvas是基于状态来绘制的。
2、画一条直线:
var canvas = document.getElementById("line"); //获取画布节点
canvas.width =1366; //设置画布的宽
canvas.height =600; //设置画布的高
if(canvas.getContext){
var ctx = line.getContext("2d");
ctx.moveTo(100,100); //移动到位置(100,100)
ctx.lineTo(500,500); //从位置(100.100)画线到 位置 (500,500)
ctx.lineTo(100,500); //从位置(500,500)画线到 位置 (100,500)
ctx.lineTo(100,100);
ctx.stroke();
}
效果图:
修改之前的代码如下:
var canvas = document.getElementById("line");
canvas.width =1366;
canvas.height =600;
if(canvas.getContext){
var ctx = line.getContext("2d");
ctx.beginPath();// 开始一段新的画
ctx.moveTo(100,100);
ctx.lineTo(500,500);
ctx.lineTo(100,500);
10 ctx.lineTo(100,100);
11 ctx.fillStyle ="#6699cc"; //设置填充颜色
ctx.fill(); //执行填充操作
ctx.lineWidth =5; //设置线宽
ctx.strokeStyle ="rgba(0,255,0,.5)"; //设置画线的颜色
ctx.stroke(); //画线(会基于之前设置的三个 lineTo的坐标位置而依次画图)
ctx.closePath(); //结束这段画
}
效果如下:
熟练之后可以用下面这段代码画出一个美丽的七巧板:
var tangram =[
{p:[{x:100,y:100},{x:300,y:300},{x:500,y:100}],color:'#CAFF67'},
{p:[{x:100,y:100},{x:300,y:300},{x:100,y:500}],color:'#6699CC'},
{p:[{x:100,y:500},{x:200,y:400},{x:300,y:500}],color:"pink"},
{p:[{x:200,y:400},{x:300,y:300},{x:400,y:400},{x:300,y:500}],color:'purple'},
{p:[{x:300,y:300},{x:400,y:200},{x:400,y:400}],color:'yellow'},
{p:[{x:400,y:200},{x:500,y:100},{x:500,y:300},{x:400,y:400}],color:'red'},
{p:[{x:300,y:500},{x:500,y:300},{x:500,y:500}],color:'orange'}
]
window.onload =function(){
var canvas = document.getElementById("line"),
i =0;
canvas.width =1366;
canvas.height =600;
if(canvas.getContext){
var context = canvas.getContext("2d");
for(i =0;i<tangram.length;i++){
draw(tangram[i],context)
}
}
}
function draw(piece,cxt){
cxt.beginPath();
cxt.moveTo(piece.p[0].x,piece.p[0].y);
var i =1;
for(;i < piece.p.length;i++){
cxt.lineTo(piece.p[i].x,piece.p[i].y);
}
cxt.closePath();
cxt.fillStyle=piece.color;
cxt.fill();
cxt.fillStyle ="#000000";
cxt.lineWidth =3;
cxt.stroke();
}
效果图:
另外我这里还做了一个Demo,当你输入自己的英文名时,你可以看到圆球跳跃的效果显示你的英文名,由于篇幅,不详说,
效果图:

具体的代码见github:
https://github.com/caibinterry/test/tree/caibin/%E8%B7%B3%E5%8A%A8%E7%9A%84%E8%8B%B1%E6%96%87%E5%90%8D
来自为知笔记(Wiz)







