画布动画和animationFrame,蛇效果

时间:2016-10-05 00:22:50

标签: javascript canvas requestanimationframe cancelanimationframe

我在画布上绘制了四个矩形,每个边都自动来回(或上下)。我想要创建的是一个蛇效果,例如我的动画以顶部的矩形开始,直到canvas.width的结尾,然后我右边的矩形将开始动画从上到下,依此类推其他矩形。我能做些什么来实现这种动画?

查看我的代码:https://jsfiddle.net/4kdrLde8/

function drawRecTop(recTop, context) {
    context.beginPath();
    context.rect(recTop.x, recTop.y, recTop.width, recTop.height);
    context.fillStyle = '#FB0202';
    context.fill();
}

function drawRecRight(recRight, context) {
    context.beginPath();
    context.rect(recRight.x , recRight.y , recRight.width, recRight.height);
    context.fillStyle = '#FB0202';
    context.fill();
}

function drawRecBottom(recBottom, context) {
    context.beginPath();
    context.rect(recBottom.x , recBottom.y , recBottom.width, recBottom.height);
    context.fillStyle = '#FB0202';
    context.fill();
}

function drawRecLeft(recLeft, context) {
     context.beginPath();
     context.rect(recLeft.x , recLeft.y , recLeft.width, recLeft.height);
     context.fillStyle = '#FB0202';
     context.fill();
}

function animate(myRectangle, canvas, context, startTime) {
    // update
    recTop.x ++;
    recRight.y ++;
    recBottom.x -- ;
    recLeft.y --;

    // clear
    context.clearRect(0, 0, canvas.width, canvas.height);

    drawRecTop(recTop, context);
    drawRecRight(recRight, context);
    drawRecBottom(recBottom, context);
    drawRecLeft(recLeft, context);


    // request new frame
    requestAnimFrame(function() {
        animate(myRectangle, canvas, context, startTime);
    });
}


var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

var recTop = {
    x: -180,
    y: 0,
    width: 150,
    height: 20
};

var recRight = {
    x: 480,
    y: 0,
    width: 20,
    height: 150
};

var recBottom = {
    x: 480,
    y: 480,
    width: 150,
    height: 20
};

var recLeft = {
    x: 0,
    y: 480,
    width: 20,
    height: 150
};

// wait one second before starting animation
setTimeout(function() {
    var startTime = (new Date()).getTime();
    animate(recTop, canvas, context, startTime);
}, 2000);

0 个答案:

没有答案