好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

利用HTML5 Canvas制作键盘及鼠标动画的实例分享

键盘控制小球移动

众所周知,我们所看到的动画实际上就是一 系列 静态画面快速切换,从而让肉眼因视觉残像产生了「画面在 活动 」的视觉效果。明白了这 一点 后,在canvas上 绘制 动画效果就显得比较 简单 了。我们只需要将某个静态图形先清除,然后在另外一个位置重新绘制,如此反复,让静态图形按照一定的轨迹进行移动,就可以产生动画效果了。

下面,我们在canvas上绘制一个实心小球,然后用键盘上的 方向键 控制小球的移动,从而产生动态效果。示例代码如下:

JavaScript Code 复制内容到剪贴板

<!DOCTY PE &nbs p; ht ML >    <html>    <head>    < ;m eta charset= "UTF-8" >    <t IT le>html5 canvas绘制可移动的小球入门示例</title>    </head>    <body onkeydown= "moveBall(event)" >       <!-- 添加canvas标签,并加上 红色 边框以便于在页面上查看 -->    <canvas id= "myCanvas"  width= "400px"  h ei ght= "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 !=  "un define d" ){            ctx.be gin Path();            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();                 br eak ;             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  K inet ic.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 @H_156_ 126 6@复制内容到剪贴板

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 {            m arg in: 0px;            padding: 0px;          }          # cont ai ner {            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. rev erse();            rightEyeTween.reverse();            noseTween.reverse();            mouthTween.reverse();          });           </script>      </body>    </html>  

观看演示

总结

以上是 为你收集整理的 利用HTML5 Canvas制作键盘及鼠标动画的实例分享 全部内容,希望文章能够帮你解决 利用HTML5 Canvas制作键盘及鼠标动画的实例分享 所遇到的问题。

如果觉得 网站内容还不错, 推荐好友。

查看更多关于利用HTML5 Canvas制作键盘及鼠标动画的实例分享的详细内容...

  阅读:21次