美文网首页
13帧动画

13帧动画

作者: 夜幕小草 | 来源:发表于2016-12-07 23:16 被阅读15次
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Canvas绘制帧动画</title>
    </head>
    <body style="padding: 100px;">
      <canvas id="canvas" width="900" height="600" style="border:1px solid #000"></canvas>
      <p></p>
      <button dir="2">上</button>
      <button dir="6">下</button>
      <button dir="0">左</button>
      <button dir="4">右</button>
    <script>
         // 1. 获取标签
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
    
        // 2. 加载图片
        // 2.1 裁剪的图片的宽高
         var clipImgWH = 256;
         var duration = 400; // ms
         var dir = 0; // 默认向左
    
        var image = new Image();
        image.src = 'images/girl.png';
        image.addEventListener('load', function () {
            // 备份指针
            var self = this;
    
            var index = 0;
            setInterval(function () {
                // 清屏
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                // 绘制
                ctx.drawImage(self, index * clipImgWH, dir * clipImgWH, clipImgWH, clipImgWH, 200, 200, clipImgWH, clipImgWH );
                index += 1;
                // 对列数求余  --> 让图片循环
                index %= 8;
            }, duration);
        });
    
        // 改变方向
        var buttonList = document.querySelectorAll("button");
        for(var i=0; i<buttonList.length; i++){
            buttonList[i].addEventListener('click', function () {
                 dir =  this.getAttribute('dir'); // 改变方向
            });
        }
    
    </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:13帧动画

          本文链接:https://www.haomeiwen.com/subject/xxdhmttx.html