0

我创建了一个基本的 HTML5 图像滑块,其中图像在画布中从上到下移动。我希望所有图像都以 5 度角旋转。当我尝试它时,画布似乎有些失真,并且图像没有正确旋转。

我已经尝试过下面帖子中提到的旋转方法

如何在 html 5 画布上旋转单个对象?

小提琴 - http://jsfiddle.net/DS2Sb/

代码

this.createImage = function (image, width, height) {

    var fbWallImageCanvas = document.createElement('canvas');
    var fbWallImageCanvasContext = fbWallImageCanvas.getContext('2d');
    fbWallImageCanvas.width = width;
    fbWallImageCanvas.height = height;

    fbWallImageCanvasContext.save();
    fbWallImageCanvasContext.globalAlpha = 0.7;
    this.rotateImage(image, 0, 0, width, height, 5, fbWallImageCanvasContext);
    fbWallImageCanvasContext.drawImage(image, width, height);
    fbWallImageCanvasContext.restore();
    return fbWallImageCanvas;
};

this.rotateImage = function (image, x, y, width, height, angle, context) {

    var radian = angle * Math.PI / 180;
    context.translate(x + width / 2, y + height / 2);
    context.rotate(radian);
    context.drawImage(image, width / 2 * (-1), height / 2 * (-1), width, height);
    context.rotate(radian * (-1));
    context.translate((x + width / 2) * (-1), (y + height / 2) * (-1));

};
4

2 回答 2

1

您看到的失真是由于旋转的图像只适合更大的画布。所以我们看到的是旋转图像上的矩形视图。
计算并不容易让事情正确完成,但不是预先计算旋转的图像,您可以在绘制它们时旋转它们,这样您也可以随时更改角度(顺便说一下不透明度)。

所以我简化了createImage,以便它只将图像存储在画布中(绘制画布比绘制图像更快):

this.createImage = function(image , width, height) {
    var fbWallImageCanvas = document.createElement('canvas');
    fbWallImageCanvas.width = width;
    fbWallImageCanvas.height = height;  
            var fbWallImageCanvasContext = fbWallImageCanvas.getContext('2d');
    fbWallImageCanvasContext.drawImage(image,0,0);
    return fbWallImageCanvas;
};

我改变了drawItem,所以它绘制了旋转的图像:

this.drawItem = function(ct) {
        var angle = 5;
        var radian = angle * Math.PI/180;
        ct.save();
        ct.translate(this.x + this.width/2 , this.y + this.height/2);
        ct.rotate(radian);
        ct.globalAlpha = 0.7;
        ct.drawImage(fbc, - this.width/2, -this.height/2 , this.width, this.height);
        ct.restore();
        this.animate();
    };

您可能想要重构它,但您看到了这个想法。

小提琴在这里:http: //jsfiddle.net/DS2Sb/1/

于 2013-10-29T13:09:06.663 回答
0

这是我不久前创建的一个小型 html5 教程的链接:

https://bitbucket.org/Garlov/html5-sidescroller-game-source

这是旋转代码:

// save old coordinate system
ctx.save(); 
// move to the middle of where we want to draw our image
ctx.translate(canvas.width/2, canvas.height-64);
// rotate around that point
ctx.rotate(0.02 * (playerPosition.x));
//draw playerImage
ctx.drawImage(playerImage, -playerImage.width/2, -playerImage.height/2);
//and restore coordniate system to default
ctx.restore();
于 2013-10-29T10:08:30.727 回答