setTimeout()不适用于动画功能|动画不起作用

时间:2017-01-22 04:45:41

标签: javascript animation html5-canvas

我正在尝试构建一个非常简单的动画功能。我使用本教程来构建我的项目:

https://www.youtube.com/watch?v=hUCT4b4wa-8

单击按钮后的结果应该是一个从左到右移动页面的绿框。单击按钮时,没有任何反应,我也没有收到任何控制台错误。

这是我的小提琴: https://jsfiddle.net/xkhpmrtu/7/

这是我的代码片段:

<!DOCTYPE html>

<head>

    <meta charset="utf-8" />

    <style type="text/css">

        canvas {
            border: 1px solid #666;
        }

    </style>

    <script type="application/javascript" language="javascript">
        function anim(x,y) {
            var canvas = document.getElementById('canvas');//reference to canvas element on page
            var ctx = canvas.getContext('2d');//establish a 2d context for the canvas element
            ctx.save();//save canvas state if required (not required for the tutoriral anaimation, but doesn't hurt the script so it stays for now)
            ctx.clearRect(0, 0, 550, 400);//clears the canvas for redrawing the scene.
            ctx.fillStyle = "rgba(0,200,0,1)";//coloring the rectangle
            ctx.fillRect = (x, 20, 50, 50);//drawing the rectangle
            ctx.restore();//this restores the canvas to it's original state when we saved it on (at the time) line 18
            x += 5; //increment the x position by some numeric value
            var loopTimer = setTimeout('draw('+x+','+y+')', 2000);// setTimeout is a function that 
    </script>

</head>

<body>

    <button onclick="animate(0,0)">Draw</button>

    <canvas id="canvas" width="550" height="400"></canvas>

</body>

知道我做错了吗?

1 个答案:

答案 0 :(得分:1)

我刚看了一下教程链接。如果一个主要的大拇指向下,我会给出一个大拇指,因为它演示了如何不动画以及如何在Javascript中做很多其他事情。

首先是脚本标签,它有什么问题

// type and language default to the correct setting for javascrip
// <script type="application/javascript" language="javascript">
<script>

    function anim(x,y) {
        // get the canvas once. Getting the canvas for each frame of an
        // animation will slow everything down. Same for ctx though will not
        // create as much of a slowdown it is not needed for each frame
        // var canvas = document.getElementById('canvas');
        // var ctx = canvas.getContext('2d');
        // Dont use save unless you have to. It is not ok to add it if not needed
        // ctx.save();
        // dont use literal values, canvas may change size
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = "rgba(0,200,0,1)";
        // this line is wrong should be ctx.fillRect(x, 20, 50, 50). It is correct in the video               
        ctx.fillRect = (x, 20, 50, 50);//drawing the rectangle
        // restore not needed
        //ctx.restore();

        x += 5; //increment the x position by some numeric value
        // creating a string for a timer is bad. It invokes the parser and is slooowwwwww... 
        // For animations you should avoid setTimeout altogether and use
        // requestAnimationFrame
        // var loopTimer = setTimeout('draw('+x+','+y+')', 2000);
        requestAnimationFrame(draw);
     // you were missing the closing curly.
     }
</script>

啧啧有很多错误。由于它已接近5岁,因此可以原谅。你应该寻找更多更多的教程,因为5年是计算机技术的永恒。

以下是如何正确完成的。

// This script should be at the bottom of the page just befor the closing body tag
// If not you need to use the onload event to start the script.


// define a function that starts the animation
function startAnimation() {
    animating = true; // flag we are now animating
    x = 10;
    y = 10;
    // animation will start at next frame or restart at next frame if already running
}
  // define the animation function

function anim() {
  if (animating) { // only draw if animating
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "red"; //coloring the rectangle
    ctx.fillRect(x, y, 50, 50); //drawing the rectangle
    x += xSpeed;

  }
  // set animation timer for next frame
  requestAnimationFrame(anim);
}


// add a click listener to the start button. It calls the supplied function every time you click the button
startAnimButton.addEventListener("click", startAnimation);

const ctx = canvas.getContext('2d'); // get the 2d rendering context

// set up global variables to do the animation
var x, y, animating;
animating = false; // flag we are not animating

const xSpeed = 50 / 60; // Speed is 50 pixels per second at 60fps
                        // dont slow the animation down via frame rate
                        // slow it down by reducing speed.
                        // You only slow frame rate if the machine
                        // can not handle the load.

// start the animation loop
requestAnimationFrame(anim);
canvas {
  border: 1px solid #666;
}
<!-- don't add events inline -->
<button id="startAnimButton">Draw</button>
<canvas id="canvas" width="512" height="128"></canvas>