Html5 Canvas旋转单个元素

时间:2012-10-05 17:14:50

标签: javascript html5 html5-canvas

我知道在stackoverflow上已经有很多类似的问题,但是,我仍然无法弄清楚如何去做。我想只旋转球纹理。用计时器调用draw:

var canvas;
var ctx;
var width;
var height;
var ready;
var textures;
var loadIndex;
var loadCount;
var keyCodes;
var mouseLoc;

var playerX;
var playerY;
var playerVelocity;

function init() {
    canvas = document.getElementById('game');
    ctx = canvas.getContext("2d");
    width = canvas.width;
    height = canvas.height;
    textures = [];
    loadingCount = 0;
    keyCodes = [];
    mouseLoc = {};

    playerX = 0;
    playerY = 0;
    playerVelocity = 6;

    textures['Background'] = loadTexture('./textures/Background.png');
    textures['Ball'] = loadTexture('./textures/Ball.png');

    setInterval(function(){ 
        if(loadingCount == 0) {
            update();
            draw();
        }
    }, 50);
}

function update(){
    if(keyCodes[37])
        playerX -= playerVelocity;
    if(keyCodes[38])
        playerY -= playerVelocity;
    if(keyCodes[39])
        playerX += playerVelocity;
    if(keyCodes[40])
        playerY += playerVelocity;
}

function draw() {
    //ctx.clearRect(0, 0, width, height);
    //ctx.beginPath();
    drawBackground();
    drawPlayer();
    //ctx.closePath();
    //ctx.fill();
}

function drawBackground(){
    ctx.drawImage(textures['Background'], 0, 0, width, height);
}

function drawPlayer(){
    ctx.save();
    ctx.rotate(0.17);
    ctx.drawImage(textures['Ball'], playerX, playerY, 100, 100);
    ctx.restore();
}

function loadTexture(src){
    var image = new Image();
    image.src = src;
    loadingCount++;
    image.onload = function(){
        loadingCount--;
    };
    return image;
}

document.onkeydown = function(evt){
    keyCodes[evt.keyCode] = true;
    evt.returnValue = false;
}
document.onkeyup = function(evt){
    keyCodes[evt.keyCode] = false;
}

document.onmousemove = function(evt){
    mouseLoc.x = evt.layerX;
    mouseLoc.y = evt.layerY;
}
document.onmousedown = function(evt){
    mouseLoc.down = true;
}
document.onmouseup = function(evt){
    mouseLoc.down = false;
}

init();

3 个答案:

答案 0 :(得分:1)

您只需要保存并恢复画布的状态(状态机)

function drawPlayer(){
    ctx.save();
    ctx.rotate(0.17);
    ctx.drawImage(textures['Ball'], playerX, playerY, 100, 100);
    ctx.restore();
}

答案 1 :(得分:1)

假设你想让球继续的幻觉旋转,你应该增加每个画框的旋转角度。

如上所述,您的代码会在每帧上为球提供0.17弧度的固定旋转。

var frame = 0;

function drawPlayer() {
    ctx.save();
    ctx.rotate(0.17 * frame);
    ...
    ctx.restore();
}

function draw() {
    ++frame;
    drawPlayer();
    ...
}

答案 2 :(得分:1)

您希望使用增量时间来计算旋转距离。也就是说,从最后一帧开始经过的时间。如果您的浏览器打嗝并在这里或那里丢失一个框架,这将使您的旋转更顺畅。

因此,存储每帧的时间,以便您可以在帧之间进行比较,并将旋转速度设置为每秒弧度。