当前位置: 代码迷 >> .NET相关 >> canvas作图简易动画
  详细解决方案

canvas作图简易动画

热度:135   发布时间:2016-04-24 02:46:40.0
canvas绘制简易动画

在canvas画布中制作动画相对来说很简单,实际上就是不断变化的坐标、擦除、重绘的过程

1、使用setInterval方法设置动画的间隔时间。

setInterval(code,millisec) setInterval方法html中固有方法,这个方法接受两个参数,第一个函数表示执行动画的函数,第二个参数为间隔时间,单位是(毫秒)。

2、用来绘图的函数

1)通过不断变换X和Y的坐标实现动画的效果。

2)在该函数中先用clearRect方法将画布整体或者局部擦除。

擦除图像clearRect方法:

context.clearRect(x,y,width,height);

x是指我们起点的横坐标,y是指我们起点的纵坐标,width是指擦子的长度,height是指擦子的高度。

 

<!DOCTYPE html><html>    <head>        <meta charset="utf-8">        <title>canvas绘制动画</title>        <script src="js/canvas.js" type="text/javascript" charset="utf-8"></script>    </head>    <body onload="draw('canvas')">                <canvas id="canvas" width="200" height="200"></canvas>    </body></html>

 

var context;var i,j;var width,height;function draw(id){    var canvas = document.getElementById(id);    context = canvas.getContext('2d');    width = canvas.width;    height = canvas.height;    context.fillStyle = 'green';    context.fillRect(0,0,width,height);    setInterval(painting,100);    i = 0;    j = 0;}function painting(){    //例子一:    //context.fillStyle = 'red';    //context.fillRect(i,i,10,10);    //context.fillRect(i,200-j,10,10);    //i++;    //j++;    //例子二:    context.fillStyle = 'white';    context.clearRect(i,20,1,10);    i++;    }