canvas制作动画效果
步骤
-
使用setInterval方法设置动画的间隔时间
setInterval(code,millisec)
第一个参数表示执行动画的函数,第二个参数为间隔时间(单位是毫秒) -
用来绘图的函数
context.fillRect(x,y,width,height);
(1)通过不断的变换X和Y的坐标来实现动画效果
(2)在该函数中先用clearRect方法将画布整体或是局部擦除
x,y是指起点的横坐标和纵坐标;width,height是擦子的长度和高度
核心代码
var i ;
var context;
var width,height;
function draw(id){
var canvas = document.getElementById(id);//获取元素
context = canvas.getContext('2d');//获取上下文
width = canvas.width;
height = canvas.height;
setInterval(paintingg,100);
i = 0;
}
function painting(){
context.fillStyle="red";//填充颜色
context.fillRect(i,0,10,10);
i = i + 20;//可以改变得到不同效果
}
function paintingg(){
context.fillStyle="red";//填充颜色
context.clearRect(0,0,width,height);
context.fillStyle="green";
context.fillRect(i,20,10,10);
i=i+20;
}