学习HTML5, Canvas及简单动画的使用

通过在CSDN中的一些简单课程学习,跟随老师联系,做了如下的月亮,太阳和地球的运动效果。纪录在文章中,用于下次使用。

准备工作如下:

1. 使用三张背景图片

太阳 月亮 地球

2. 在HTML页面中定义一个CANVAS

1 <body>
2     <div style="background-color:green;text-align:center ;">
3         <canvas id="c" style="background-color:red;" width="300" height="300"></canvas>
4     </div>
5 </body>

3. 编写JS代码,使用canvas的API接口。 如 :translate, drawImage 和arc 等方法

 1   <script type="text/javascript">
 2 
 3         var sun = new Image(),
 4             moon = new Image(),
 5             earth = new Image();
 6 
 7         function init() {
 8             sun.src = "html5image/sun.png";
 9             moon.src = "html5image/moon.png";
10             earth.src = "html5image/earth.png";
11 
12             window.requestAnimationFrame(draw);
13         }
14 
15         function draw() {
16             var c = document.getElementById("c");
17             var ctx = c.getContext("2d");
18 
19             ctx.globalCompositeOperation = "destination-over";
20             ctx.clearRect(0, 0, 300, 300);
21             ctx.fillStyle = "rgba(0,0,0,4)";
22             ctx.strokeStyle = "rgba(0,153,255,0.4)";
23             ctx.save();// save current status
24 
25             ctx.translate(150, 150);
26 
27             //earth
28             var time = new Date();
29             ctx.rotate((2 * Math.PI / 60) * time.getSeconds() + (2 * Math.PI / 60000) * time.getMilliseconds());
30             ctx.translate(105, 0);
31             ctx.drawImage(earth, -12, -12);
32 
33             //moon
34             ctx.save();
35             ctx.rotate((2 * Math.PI / 6) * time.getSeconds() + (2 * Math.PI / 6000) * time.getMilliseconds());
36             ctx.translate(0, -28.5);
37             ctx.drawImage(moon, -3.5, -3.5);
38             ctx.restore(); //back to moon save
39 
40             //the moving path
41             ctx.restore(); //back to the begin to draw earth
42             ctx.beginPath();
43             ctx.arc(150, 150, 105, 0, Math.PI * 2, false);
44             ctx.stroke();
45 
46             //sun
47             ctx.drawImage(sun, 0, 0, 300, 300);
48 
49             //exec an animation use the frame and the action is draw. 
50             window.requestAnimationFrame(draw);
51         }
52 
53         init();
54     </script>


如果需要知道更详细的步骤,请参考: http://edu.csdn.net/course/detail/1488

最后附上效果图:

 动态效果图,请查看下面链接 。 http://ihelper.eu-gb.mybluemix.net/

thanks

原文地址:https://www.cnblogs.com/lubu123456/p/4876189.html