将JS动画重置为稳定的空白画布

时间:2014-01-10 18:52:59

标签: javascript animation canvas

我正在尝试从onclick函数中清除运行JS动画的画布屏幕。 不是恢复到稳定的空白画布(应该保持这样直到再次触发),动画会在清除后立即启动。

这是我用来清除画布的编码

JS

     function clearleftcanvas()
{
    canvas = document.getElementById('canvas1');
    ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}

HTML

<input type="button" value="reset animation" onclick="clearleftcanvas()">

如果您需要更多信息,请与我们联系。

编辑:动画代码

JS

    <script>
    var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');
var W = canvas.width = 500 //window.innerWidth;
var H = canvas.height = 500 //window.innerHeight;
var x = Math.floor(Math.random()*W);
var y = Math.floor(Math.random()*H);
var speed = 1;
function animate() {
reqAnimFrame = window.mozRequestAnimationFrame    ||
            window.webkitRequestAnimationFrame ||
            window.msRequestAnimationFrame     ||
            window.oRequestAnimationFrame
            ;
reqAnimFrame(animate);
x += speed;
if(x <= 0 || x >= W - 300){
    speed = -speed;
    }
    draw();
}
function draw() {  
ctx.beginPath();
 ctx.fillStyle = "clear";
function randCoord(){
return Math.floor((Math.random()*500)+1);
  }
ctx.lineWidth=  Math.random() * (0.5 - 0.01) + 0.01;
ctx.moveTo(randCoord(0),randCoord(0));
ctx.lineTo(randCoord(0),randCoord(0));
ctx.lineTo(randCoord(0),randCoord(0));
ctx.lineTo(randCoord(0),randCoord(0));
ctx.lineTo(randCoord(0),randCoord(0));
ctx.lineTo(randCoord(0),randCoord(0));
ctx.lineTo(randCoord(0),randCoord(0));
ctx.lineTo(randCoord(0),randCoord(0));
ctx.lineTo(randCoord(0),randCoord(0));
ctx.lineTo(randCoord(0),randCoord(0));
ctx.stroke();
ctx.scale(1,1)
ctx.fill();
}
animate();
</script>

HTML

<canvas id="canvas1" width="500" height="500" style="border:1px solid #FFFFF;">
</canvas>

1 个答案:

答案 0 :(得分:1)

给动画一个间隔,当你清除它时使用。

var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;
window.cancelAnimationFrame(interval);

代码太大了,无法在此发布,但您可以在此处看到快速编写的工作版本。 http://jsfiddle.net/4bVBa/1/