HTML5 Canvas 2d在同一点闪烁

时间:2013-10-20 15:43:23

标签: javascript html5 animation canvas

我使用HTML5画布在JavaScript中制作了一个简单的动画。我的问题是动画总是在同一点上闪烁。有趣的是,动画重置时没有发生这种情况。

所以这是我用于绘图的代码:

draw: function() {
    var canvas = background.ct; 
    canvas.clearRect(0,0, WINDOW_WIDTH, WINDOW_HEIGHT);
    for (var i = 0; i < 12; i++)
    {
        var sX = startX+((SLOT_WIDTH+20)*i)+mod;
        drawCard(
                {x: sX,
                    y: startY,
                    color: "#0A5",
                    ctx: canvas});
        if (resetX == sX && mod != 0) //resets the animation
            {
                console.log('resetting at '+mod);
                mod = 0;
            }

        if ( i == 1 && resetX == 0) //get reset-point
            {
                resetX = startX+((SLOT_WIDTH+20)*i)+mod;
            }


    }
    mod++;

}

这是drawCard函数:

/*
 * Draw 1 Card where x/y is the center of the card
 */
 function drawCard(pos)
 {
if (!pos.x || !pos.y)
    return;

var c_top_left_x = pos.x - SLOT_WIDTH / 2;
var c_top_y = pos.y - SLOT_HEIGHT / 2;
var c_top_right_x = pos.x + SLOT_WIDTH / 2;
var c_bot_left_x = pos.x - SLOT_WIDTH / 2;
var c_bot_right_x = pos.x + SLOT_WIDTH / 2;
var c_bot_y = pos.y + SLOT_HEIGHT / 2;

var canvas = pos.ctx;
canvas.beginPath();
canvas.moveTo(c_top_left_x + RAD, c_top_y);
canvas.lineTo(c_top_right_x - RAD, c_top_y);
canvas.arcTo(c_top_right_x, c_top_y, c_top_right_x, c_top_y + RAD, RAD);
canvas.lineTo(c_bot_right_x, c_bot_y - RAD);
canvas.arcTo(c_bot_right_x, c_bot_y, c_bot_right_x - RAD, c_bot_y, RAD);
canvas.lineTo(c_bot_left_x + RAD, c_bot_y);
canvas.arcTo(c_bot_left_x, c_bot_y, c_bot_left_x, c_bot_y - RAD, RAD);
canvas.lineTo(c_top_left_x, c_top_y + RAD);
canvas.arcTo(c_top_left_x, c_top_y, c_top_left_x + RAD, c_top_y, RAD);
canvas.fillStyle = pos.color;

canvas.fill();

}

mod是用于创建动作的变量。

完整来源位于http://jsfiddle.net/Kafioin/ymddh/

1 个答案:

答案 0 :(得分:2)

如果您在drawCard中移除/修复此行,则会停止闪烁:

if (!pos.x || !pos.y) return;

当pos.x == 0时发生闪烁。由于!0为真,因此不会对该动画循环执行绘制。