欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

HTML5 Canvas draw方法制作动画效果示例

程序员文章站 2023-12-10 14:08:40
首先要准备一张有连续帧的图片,然后利用HTML5 Canvas的draw方法在不同的时间间隔绘制不同的帧,这样看起来就像动画在播放,关键技术点及实例代码如下,感兴趣的朋友可以参考下哈,希... 13-07-11...
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帧的大雁飞行图片实现的效果:
HTML5 Canvas draw方法制作动画效果示例 
源图像:
HTML5 Canvas draw方法制作动画效果示例 
程序代码:

复制代码
代码如下:

<!doctype html>
<html>
<head>
<meta http-equiv="x-ua-compatible" content="chrome=ie8">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>canvas mouse event demo</title>
<link href="default.css" rel="stylesheet" />
<script>
var ctx = null; // global variable 2d context
var started = false;
var mtext_canvas = null;
var x = 0, y =0;
var frame = 0; // 22 5*5 + 2
var imageready = false;
var myimage = null;
var px = 300;
var py = 300;
var x2 = 300;
var y2 = 0;
window.onload = function() {
var canvas = document.getelementbyid("animation_canvas");
console.log(canvas.parentnode.clientwidth);
canvas.width = canvas.parentnode.clientwidth;
canvas.height = canvas.parentnode.clientheight;
if (!canvas.getcontext) {
console.log("canvas not supported. please install a html5 compatible browser.");
return;
}
// get 2d context of canvas and draw rectangel
ctx = canvas.getcontext("2d");
ctx.fillstyle="black";
ctx.fillrect(0, 0, canvas.width, canvas.height);
myimage = document.createelement('img');
myimage.src = "../robin.png";
myimage.onload = loaded();
}
function loaded() {
imageready = true;
settimeout( update, 1000/30);
}
function redraw() {
ctx.clearrect(0, 0, 460, 460)
ctx.fillstyle="black";
ctx.fillrect(0, 0, 460, 460);
// find the index of frames in image
var height = myimage.naturalheight/5;
var width = myimage.naturalwidth/5;
var row = math.floor(frame / 5);
var col = frame - row * 5;
var offw = col * width;
var offh = row * height;
// first robin
px = px - 5;
py = py - 5;
if(px < -50) {
px = 300;
}
if(py < -50) {
py = 300;
}
//var rate = (frame+1) /22;
//var rw = math.floor(rate * width);
//var rh = math.floor(rate * height);
ctx.drawimage(myimage, offw, offh, width, height, px, py, width, height);
// second robin
x2 = x2 - 5;
y2 = y2 + 5;
if(x2 < -50) {
x2 = 300;
y2 = 0;
}
ctx.drawimage(myimage, offw, offh, width, height, x2, y2, width, height);
}
function update() {
redraw();
frame++;
if (frame >= 22) frame = 0;
settimeout( update, 1000/30);
}
</script>
</head>
<body>
<h1>html canvas animations demo - by gloomy fish</h1>
<pre>play animations</pre>
<div id="my_painter">
<canvas id="animation_canvas"></canvas>
</div>
</body>
</html>

发现上传透明png格式有点问题,所以我上传不透明的图片。可以用其它图片替换,替换以后请修改最大帧数从22到你的实际帧数即可运行。