2013-10-29 165 views
0

我創建了基本的HTML5圖像滑塊,圖像在畫布中從上到下移動。 我想要所有的圖像在5度角旋轉。當我嘗試它時,畫布上似乎有一些變形,並且圖像未正確旋轉。畫布圖像旋轉中的問題

我試過在下面文章中提到旋轉的方法

How do I rotate a single object on an html 5 canvas?

小提琴 - 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)); 

}; 
+0

您的代碼將兩次繪製圖像的屏幕外的畫布:一個旋轉,一個不旋轉。那是你想要的代碼嗎? – markE

回答

1

您所看到的失真是由於這樣的事實,一個旋轉的圖像只能以一個更大的畫布。所以我們看到的是旋轉圖像上的矩形視圖。
計算並不是很容易完成正確的事情,但不是預先計算旋轉的圖像,而是可以在繪製它們時旋轉它們,這樣可以隨時更改角度(並且不透明度也是btw) 。

所以我簡單的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/

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();