HTML5 Canvas动画效果演示
主要思想:
首先要准备一张有连续帧的图片,然后利用HTML5 Canvas的draw方法在不同的时间间隔绘制不同的帧,这样看起来就像动画在播放。
关键技术点:
JavaScript 函数setTimeout()有两个参数,第一个是参数可以传递一个JavaScript方法,
另外一个参数代表间隔时间,单位为毫秒数。代码示例:
setTimeout( update, 1000/30);
Canvas的API-drawImage()方法,需要指定全部9个参数:
ctx.drawImage(myImage, offw, offh, width,height, x2, y2, width, height);
其中offw, offh是指源图像的起始坐标点,width, height表示源图像的宽与高,x2,y2表
示源图像在目标Canvas上的起始坐标点。
一个22帧的大雁飞行图片实现的效果:
源图像:
程序代码:
Canvas Mouse Event Demo <script> <br />var ctx = null; // global variable 2d context <br />var started = false; <br />var mText_canvas = null; <br />var x = 0, y =0; <br />var frame = 0; // 22 5*5 + 2 <br />var imageReady = false; <br />var myImage = null; <br />var px = 300; <br />var py = 300; <br />var x2 = 300; <br />var y2 = 0; <br />window.onload = function() { <br />var canvas = document.getElementById("animation_canvas"); <br />console.log(canvas.parentNode.clientWidth); <br />canvas.width = canvas.parentNode.clientWidth; <br />canvas.height = canvas.parentNode.clientHeight; <br />if (!canvas.getContext) { <br />console.log("Canvas not supported. Please install a HTML5 compatible browser."); <br />return; <br />} <br />// get 2D context of canvas and draw rectangel <br />ctx = canvas.getContext("2d"); <br />ctx.fillStyle="black"; <br />ctx.fillRect(0, 0, canvas.width, canvas.height); <br />myImage = document.createElement('img'); <br />myImage.src = "../robin.png"; <br />myImage.onload = loaded(); <br />} <br />function loaded() { <br />imageReady = true; <br />setTimeout( update, 1000/30); <br />} <br />function redraw() { <br />ctx.clearRect(0, 0, 460, 460) <br />ctx.fillStyle="black"; <br />ctx.fillRect(0, 0, 460, 460); <br />// find the index of frames in image <br />var height = myImage.naturalHeight/5; <br />var width = myImage.naturalWidth/5; <br />var row = Math.floor(frame / 5); <br />var col = frame - row * 5; <br />var offw = col * width; <br />var offh = row * height; <br />// first robin <br />px = px - 5; <br />py = py - 5; <br />if(px < -50) { <br />px = 300; <br />} <br />if(py < -50) { <br />py = 300; <br />} <br />//var rate = (frame+1) /22; <br />//var rw = Math.floor(rate * width); <br />//var rh = Math.floor(rate * height); <br />ctx.drawImage(myImage, offw, offh, width, height, px, py, width, height); <br />// second robin <br />x2 = x2 - 5; <br />y2 = y2 + 5; <br />if(x2 < -50) { <br />x2 = 300; <br />y2 = 0; <br />} <br />ctx.drawImage(myImage, offw, offh, width, height, x2, y2, width, height); <br />} <br />function update() { <br />redraw(); <br />frame++; <br />if (frame >= 22) frame = 0; <br />setTimeout( update, 1000/30); <br />} <br /></script>
HTML Canvas Animations Demo - By Gloomy Fish
发现上传透明PNG格式有点问题,所以我上传不透明的图片。可以用其它图片替换,替换以后请修改最大帧数从22到你的实际帧数即可运行。