html5 canvas - 同时旋转和移动图像

时间:2011-09-21 18:58:33

标签: javascript animation html5-canvas

我已经找到了如何使用画布旋转图像,但是我在创建动画时遇到了问题,动画会同时旋转和移动图像。这就是我已经拥有的:

var img;
var context;
var processID;
var i = 0;
var rectWidth = 64;
var rectHeight = 64;
window.onload = function(){
        var canvas = document.getElementById("canvas");  
        context = canvas.getContext("2d");
        context.translate(canvas.width / 2, canvas.height / 2);
        processID = setInterval(draw,1000/100);
    }
    function draw() { 
        if(i <= 360) {
            context.clearRect(-canvas.width / 2, -canvas.width / 2, canvas.width, canvas.height);       
            context.strokeRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
            context.rotate(1 * Math.PI / 180);
            i++;
        } else {
            clearInterval(processID);
        }  
    }

所以现在我希望我的方块在旋转时移动到顶部。我真的迷失在这里,并希望得到一些帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用translate方法,或更一般地使用transform方法。有关您可以执行的操作以及the docs

的参考,请参阅the wiki page for Transformation Matrices

答案 1 :(得分:0)

幸运的是,我自己找到了答案:

var img;
var context;
var processID;
var i = 0;
var rectWidth = 64;
var rectHeight = 64;
window.onload = function(){
    var canvas = document.getElementById("canvas");  
    context = canvas.getContext("2d");
    processID = setInterval(draw,1000/100);
}
function draw() { 
    if(i <= 360) {
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.save();
        context.translate(canvas.width / 2, i+(canvas.height / 2));
        context.rotate(i * Math.PI / 180);
        context.strokeRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
        context.restore();
        i++;
    } else {
        clearInterval(processID);
    }  
}