HTML5 Canvas动画效果演示
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
HTML5Canvas动画效果演示
主要思想:
首先要准备一张有连续帧的图片,然后利用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帧的大雁飞行图片实现的效果:
源图像:
程序代码:
[javascript]view plain copy
1.
2.
3.
4.
5.
6.
7.
8.
9.var ctx = null; // global variable 2d context
10.var started = false;
11.var mText_canvas = null;
12.var x = 0, y =0;
13.var frame = 0; // 22 5*5 + 2
14.var imageReady = false;
15.var myImage = null;
16.var px = 300;
17.var py = 300;
18.var x2 = 300;
19.var y2 = 0;
20. window.onload = function() {
21.var canvas = document.getElementById("animation_canvas");
22. console.log(canvas.parentNode.clientWidth);
23. canvas.width = canvas.parentNode.clientWidth;
24. canvas.height = canvas.parentNode.clientHeight;
25.
26.if (!canvas.getContext) {
27. console.log("Canvas not supported. Please install a HTML5 co
mpatible browser.");
28.return;
29. }
30.
31.// get 2D context of canvas and draw rectangel
32. ctx = canvas.getContext("2d");
33. ctx.fillStyle="black";
34. ctx.fillRect(0, 0, canvas.width, canvas.height);
35. myImage = document.createElement('img');
36. myImage.src = "../robin.png";
37. myImage.onload = loaded();
38. }
39.
40.function loaded() {
41. imageReady = true;
42. setTimeout( update, 1000/30);
43. }
44.
45.function redraw() {
46. ctx.clearRect(0, 0, 460, 460)
47. ctx.fillStyle="black";
48. ctx.fillRect(0, 0, 460, 460);
49.
50.// find the index of frames in image
51.var height = myImage.naturalHeight/5;
52.var width = myImage.naturalWidth/5;
53.var row = Math.floor(frame / 5);
54.var col = frame - row * 5;
55.var offw = col * width;
56.var offh = row * height;
57.
58.// first robin
59. px = px - 5;
60. py = py - 5;
61.if(px < -50) {
62. px = 300;
63. }
64.if(py < -50) {
65. py = 300;
66. }
67.
68.//var rate = (frame+1) /22;
69.//var rw = Math.floor(rate * width);
70.//var rh = Math.floor(rate * height);
71. ctx.drawImage(myImage, offw, offh, width, height, px, py, width,
height);
72.
73.// second robin
74. x2 = x2 - 5;
75. y2 = y2 + 5;
76.if(x2 < -50) {
77. x2 = 300;
78. y2 = 0;
79. }
80. ctx.drawImage(myImage, offw, offh, width, height, x2, y2, width,
height);
81.
82. }
83.
84.function update() {
85. redraw();
86. frame++;
87.if (frame >= 22) frame = 0;
88. setTimeout( update, 1000/30);
89. }
90.
91.
92.
93.
94.
HTML Canvas Animations Demo - By Gloomy Fish
95.
Play Animations
96.
97.