JavaScript Canvas - 窗口调整大小重绘

标签 javascript canvas

http://jsfiddle.net/27WVW/1/

我有一个 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/

相关文章:

javascript - 使用 JQUERY 选择的 cb 列表的复选框过滤

Javascript Base64 图像数据已损坏/无效?

javascript - 基于嵌套属性值删除列表中项目的功能方法

javascript - 调整窗口大小时得到错误的值

javascript - 如何让我的文本显示在 <canvas> 中

javascript - 三种js更新纹理生成Canvas的最佳性能方式

HTML5 Canvas 动画偶发抖动/犹豫/卡顿

javascript - HTML5 图表无法呈现

Python:在不涉及鼠标的任何事情上使用 .bind() 时遇到问题

javascript - CamanJS 恢复和旋转修复