键盘控制小球移动
众所周知,我们所看到的动画实际上就是一系列静态画面快速切换,从而让肉眼因视觉残像产生了「画面在活动」的视觉效果。明白了这一点后,在canvas上绘制动画效果就显得比较简单了。我们只需要将某个静态图形先清除,然后在另外一个位置重新绘制,如此反复,让静态图形按照一定的轨迹进行移动,就可以产生动画效果了。
下面,我们在canvas上绘制一个实心小球,然后用键盘上的方向键控制小球的移动,从而产生动态效果。示例代码如下:
JavaScript Code复制内容到剪贴板
    - <!DOCTYPE html>    
- <html>    
- <head>    
- <meta charset="UTF-8">    
- <title>html5 canvas绘制可移动的小球入门示例</title>    
- </head>    
- <body onkeydown="moveBall(event)">    
-    
- <!-- 添加canvas标签,并加上红色边框以便于在页面上查看 -->    
- <canvas id="myCanvas" width="400px" height="300px" style="border: 1px solid red;">    
- 您的浏览器不支持canvas标签。    
- </canvas>    
-    
- <script type="text/javascript">    
- //获取Canvas对象(画布)    
- var canvas = document.getElementById("myCanvas");    
-    
- //表示圆球的类    
- function Ball(x, y ,radius, speed){    
-     this.x = x || 10;   //圆球的x坐标,默认为10    
-     this.y = y || 10;   //圆球的y坐标,默认为10    
-     this.radius = radius || 10; //圆球的半径,默认为10    
-     this.speed = speed || 5;    //圆球的移动速度,默认为5    
-         
-     //向上移动    
-     this.moveUp = function(){    
-         this.y -= this.speed;    
-         if(this.y < this.radius){    
-             //防止超出上边界    
-             this.y = this.radius;               
-         }    
-     };    
-         
-     //向右移动    
-     this.moveRight = function(){    
-         this.x += this.speed;    
-         var maxX = canvas.width - this.radius;    
-         if(this.x > maxX){    
-             //防止超出右边界    
-             this.x = maxX;              
-         }    
-     };    
-         
-     //向左移动    
-     this.moveLeft = function(){    
-         this.x -= this.speed;    
-         if(this.x < this.radius){    
-             //防止超出左边界    
-             this.x = this.radius;               
-         }    
-     };    
-         
-     //向下移动    
-     this.moveDown = function(){    
-         this.y += this.speed;    
-         var maxY = canvas.height - this.radius;    
-         if(this.y > maxY){    
-             //防止超出下边界    
-             this.y = maxY;    
-         }    
-     };    
- }    
-    
- //绘制小球    
- function drawBall(ball){    
-     if(typeof ctx != "undefined"){    
-         ctx.beginPath();    
-         ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2, false);    
-         ctx.fill();    
-     }    
- }    
-    
- //清空canvas画布    
- function clearCanvas(){    
-     if(typeof ctx != "undefined"){    
-         ctx.clearRect(0, 0, 400, 300);          
-     }    
- }    
-    
- var ball = new Ball();    
- //简单地检测当前浏览器是否支持Canvas对象,以免在一些不支持html5的浏览器中提示语法错误    
- if(canvas.getContext){      
-     //获取对应的CanvasRenderingContext2D对象(画笔)    
-     var ctx = canvas.getContext("2d");    
-     drawBall(ball);    
- }    
-    
- //onkeydown事件的回调处理函数    
- //根据用户的按键来控制小球的移动    
- function moveBall(event){    
-     switch(event.keyCode){    
-         case 37:    //左方向键    
-             ball.moveLeft();    
-             break;    
-         case 38:    //上方向键    
-             ball.moveUp();    
-             break;    
-         case 39:    //右方向键    
-             ball.moveRight();    
-             break;    
-         case 40:    //下方向键    
-             ball.moveDown();    
-             break;    
-         default:    //其他按键操作不响应    
-             return;    
-     }    
-         
-     clearCanvas();  //先清空画布    
-     drawBall(ball); //再绘制最新的小球    
- }    
- </script>    
- </body>    
- </html>    
请使用支持html5的浏览器打开以下网页以查看实际效果(使用方向键进行移动):
使用canvas绘制可移动的小球。
小丑笑脸
只需要了解很少的几个API,然后使用需要的动画参数,就能制作出这个有趣又能响应你的动作的Web动画。
第一步,画五官
这个小丑没有耳朵和眉毛,所以只剩下三官,但它的两个眼睛我们要分别绘制,所以一共是四个部分。下面先看看代码。
绘制左眼的代码
JavaScript Code复制内容到剪贴板
    - var leftEye = new Kinetic.Line({    
-        x: 150,    
-        points: [0, 200, 50, 190, 100, 200, 50, 210],    
-        tension: 0.5,    
-        closed: true,    
-        stroke: 'white',    
-        strokeWidth: 10         
-      });   
绘制右眼的代码
JavaScript Code复制内容到剪贴板
    - var rightEye = new Kinetic.Line({    
-         x: sw - 250,    
-         points: [0, 200, 50, 190, 100, 200, 50, 210],    
-         tension: 0.5,    
-         closed: true,    
-         stroke: 'white',    
-         strokeWidth: 10       
-       });   
绘制鼻子的代码
JavaScript Code复制内容到剪贴板
    - var nose = new Kinetic.Line({    
-         points: [240, 280, sw/2, 300, sw-240,280],    
-         tension: 0.5,    
-         closed: true,    
-         stroke: 'white',    
-         strokeWidth: 10    
-       });   
绘制嘴巴的代码
JavaScript Code复制内容到剪贴板
    - var mouth = new Kinetic.Line({    
-         points: [150, 340, sw/2, 380, sw - 150, 340, sw/2, sh],    
-         tension: 0.5,    
-         closed: true,    
-         stroke: 'red',    
-         strokeWidth: 10    
-       });   
你会不会觉得很失望,原来就这么简单几行代码。没错,就是这么简单,相信你对自己能成为一名Web游戏动画程序员开始有信心了! 
简单讲解一下上面的代码。Kinetic就是我们使用的js工具包。在页面的头部,我们需要这样引用它:
JavaScript Code复制内容到剪贴板
    - var mouth = new Kinetic.Line({    
-         points: [150, 340, sw/2, 380, sw - 150, 340, sw/2, sh],    
-         tension: 0.5,    
-         closed: true,    
-         stroke: 'red',    
-         strokeWidth: 10    
-       });   
其它几个分别是几个关键点,线条弹性,颜色,宽度等。这些都很容易理解。
第二步,让图动起来
这个动画之所以能吸引人,是因为它能响应你的鼠标动作,和用户有互动,这是一个成功的动画最关键的地方。如果你仔细观察,这个小丑五官的变化只是形状的变化,眼睛变大,嘴巴变大,鼻子变大,但特别的是这个变化不是瞬间变化,而是有过渡性的,这里面有一些算法,这就是最让人发愁的地方。幸运的是,这算法技术都非常的成熟,不需要我们来思考,在这些动画引擎库里都把这些技术封装成了非常简单方便的接口。下面我们来看看如何让动起来。
左眼的动画
JavaScript Code复制内容到剪贴板
    - var leftEyeTween = new Kinetic.Tween({    
-         node: leftEye,    
-         duration: 1,    
-         easing: Kinetic.Easings.ElasticEaseOut,    
-         y: -100,    
-         points: [0, 200, 50, 150, 100, 200, 50, 200]    
-       });   
右眼的动画
JavaScript Code复制内容到剪贴板
    - var rightEyeTween = new Kinetic.Tween({    
-         node: rightEye,    
-         duration: 1,    
-         easing: Kinetic.Easings.ElasticEaseOut,    
-         y: -100,    
-         points: [0, 200, 50, 150, 100, 200, 50, 200]    
-       });   
鼻子的动画
JavaScript Code复制内容到剪贴板
    - var noseTween = new Kinetic.Tween({    
-         node: nose,    
-         duration: 1,    
-         easing: Kinetic.Easings.ElasticEaseOut,    
-         y: -100,    
-         points: [220, 280, sw/2, 200, sw-220,280]    
-       });   
嘴巴的动画
JavaScript Code复制内容到剪贴板
    - var mouthTween = new Kinetic.Tween({    
-         node: mouth,    
-         duration: 1,    
-         easing: Kinetic.Easings.ElasticEaseOut,    
-         points: [100, 250, sw/2, 250, sw - 100, 250, sw/2, sh-20]    
-       });   
这些代码非常的简单,而且变量名能自释其意。稍微有点经验的程序员想看懂这些代码应该不难。基本每段代码都是让你提供一些点,指定动画动作的衰退模式和持续时间。
完整的动画代码
JavaScript Code复制内容到剪贴板
    - <!DOCTYPE HTML>    
- <html>    
-   <head>    
-     <style>    
-       body {    
-         margin: 0px;    
-         padding: 0px;    
-       }   
-       #container {    
-         background-color: black;    
-       }    
-     </style>    
-   </head>    
-   <body>    
-     <div id="container"></div>    
-     <script src="/js/lib/kinetic-v5.0.1.min.js"></script>    
-     <script defer="defer">    
-       var sw = 578;    
-       var sh = 400;    
-       var stage = new Kinetic.Stage({    
-         container: 'container',    
-         width: 578,    
-         height: 400    
-       });    
-       var layer = new Kinetic.Layer({    
-         y: -30     
-       });    
-    
-       var leftEye = new Kinetic.Line({    
-         x: 150,    
-         points: [0, 200, 50, 190, 100, 200, 50, 210],    
-         tension: 0.5,    
-         closed: true,    
-         stroke: 'white',    
-         strokeWidth: 10         
-       });    
-    
-       var rightEye = new Kinetic.Line({    
-         x: sw - 250,    
-         points: [0, 200, 50, 190, 100, 200, 50, 210],    
-         tension: 0.5,    
-         closed: true,    
-         stroke: 'white',    
-         strokeWidth: 10       
-       });    
-    
-       var nose = new Kinetic.Line({    
-         points: [240, 280, sw/2, 300, sw-240,280],    
-         tension: 0.5,    
-         closed: true,    
-         stroke: 'white',    
-         strokeWidth: 10    
-       });    
-    
-       var mouth = new Kinetic.Line({    
-         points: [150, 340, sw/2, 380, sw - 150, 340, sw/2, sh],    
-         tension: 0.5,    
-         closed: true,    
-         stroke: 'red',    
-         strokeWidth: 10    
-       });    
-    
-       layer.add(leftEye)    
-            .add(rightEye)    
-            .add(nose)    
-            .add(mouth);    
-    
-       stage.add(layer);    
-    
-       // tweens    
-    
-       var leftEyeTween = new Kinetic.Tween({    
-         node: leftEye,    
-         duration: 1,    
-         easing: Kinetic.Easings.ElasticEaseOut,    
-         y: -100,    
-         points: [0, 200, 50, 150, 100, 200, 50, 200]    
-       });     
-    
-       var rightEyeTween = new Kinetic.Tween({    
-         node: rightEye,    
-         duration: 1,    
-         easing: Kinetic.Easings.ElasticEaseOut,    
-         y: -100,    
-         points: [0, 200, 50, 150, 100, 200, 50, 200]    
-       });    
-    
-       var noseTween = new Kinetic.Tween({    
-         node: nose,    
-         duration: 1,    
-         easing: Kinetic.Easings.ElasticEaseOut,    
-         y: -100,    
-         points: [220, 280, sw/2, 200, sw-220,280]    
-       });     
-    
-       var mouthTween = new Kinetic.Tween({    
-         node: mouth,    
-         duration: 1,    
-         easing: Kinetic.Easings.ElasticEaseOut,    
-         points: [100, 250, sw/2, 250, sw - 100, 250, sw/2, sh-20]    
-       });     
-    
-       stage.getContainer().addEventListener('mouseover', function() {    
-         leftEyeTween.play();    
-         rightEyeTween.play();    
-         noseTween.play();    
-         mouthTween.play();    
-       });    
-    
-       stage.getContainer().addEventListener('mouseout', function() {    
-         leftEyeTween.reverse();    
-         rightEyeTween.reverse();    
-         noseTween.reverse();    
-         mouthTween.reverse();    
-       });    
-    
-     </script>    
-   </body>    
- </html>   
观看演示