用户登录
用户注册

分享至

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

  • 作者: huijhf5860555
  • 来源: 51数据库
  • 2021-09-21
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帧的大雁飞行图片实现的效果:
 
源图像:
 
程序代码:

复制代码
代码如下:

<!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 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到你的实际帧数即可运行。
软件
前端设计
程序设计
Java相关