我有一个 Canvas 元素,它使用 SetInterval 为背景的入口设置动画。
var c=document.getElementById("theCircle")
function drawCircle(end=2*Math.PI){
height = window.innerHeight
width = window.innerWidth
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(width/2,height/2,radius,0,end,true);
ctx.lineWidth=end/5;
ctx.closePath();
ctx.stroke();
}
function counter(start,finish,speed){
var i = start
var animation = setInterval(function(){
i += speed
if(i>=finish){clearInterval(animation)}
drawCircle(i);
}, 20)
}
counter(0.0,2*Math.PI,0.05)
在调整窗口大小时, Canvas 元素会调整大小以适合窗口,以便它始终填充页面。
window.addEventListener('resize',posFix,false);
function posFix(){
c.height = window.innerHeight
c.width = window.innerWidth
drawCircle();
}
当 Canvas 元素调整大小时,内部的绘图将被删除。正如您所看到的,我在调整大小时调用重绘,但它似乎没有正确触发。
我错过了什么?
最佳答案
正如评论中所讨论的,解决方案是清除调整大小事件中的动画间隔,然后重新启动动画。
var c = document.getElementById("theCircle"),
radius = 800;
posFix();
window.addEventListener('resize', posFix, false);
function posFix() {
c.height = window.innerHeight
c.width = window.innerWidth
clearInterval(animation);
counter(0.0, 2 * Math.PI, 0.05)
}
function drawCircle(end = 2 * Math.PI) {
height = window.innerHeight
width = window.innerWidth
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(width / 2, height / 2, radius, 0, end, true);
ctx.lineWidth = end / 5;
ctx.closePath();
ctx.stroke();
}
var animation;
function counter(start, finish, speed) {
var i = start
animation = setInterval(function () {
i += speed
if (i >= finish) {
clearInterval(animation);
}
drawCircle(i);
}, 20);
}
jsfiddle:http://jsfiddle.net/27WVW/4/
关于JavaScript Canvas - 窗口调整大小重绘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24920318/