2011-06-01 77 views
10

我在JavaScript中使用畫布在HTML 5中繪製圖像。我需要以旋轉的角度畫出它。我知道這可以通過使用畫布上下文應用旋轉(角度)函數來完成。但我需要這樣做而不旋轉畫布本身在畫布中以角度繪製圖像而不旋轉畫布

如果可能的話,請提出可能的方法。

回答

6

實際上,您可以繪製任何想要旋轉到屏幕外的畫布並將其繪製到主畫布中。我借了從谷歌IO對話驗證碼:

rotobj = rotateAndCache(myimg,myangle) 

,並在您drawcode:

rotateAndCache = function(image,angle) { 
    var offscreenCanvas = document.createElement('canvas'); 
    var offscreenCtx = offscreenCanvas.getContext('2d'); 

    var size = Math.max(image.width, image.height); 
    offscreenCanvas.width = size; 
    offscreenCanvas.height = size; 

    offscreenCtx.translate(size/2, size/2); 
    offscreenCtx.rotate(angle + Math.PI/2); 
    offscreenCtx.drawImage(image, -(image.width/2), -(image.height/2)); 

    return offscreenCanvas; 
} 

然後緩存它

mycontext.drawImage(rotobj,x_coord,y_coord) 

,如果你有一個對象這是唯一有用的它只旋轉一次角度,隨後僅進行變換。

+0

謝謝PeterT。這幾乎符合我期待的法案。再次感謝。 – Vinayak 2011-06-03 06:40:40

+0

有沒有機會與那次談話聯繫? – Alexander 2011-06-11 03:49:24

+1

@Alexander實際上我是這樣做的:http://www.google.com/events/io/2011/sessions/super-browser-2-turbo-hd-remix-introduction-to-html5-game-development.html視頻是在http://www.youtube.com/watch?v=yEocRtn_j9s – PeterT 2011-06-12 00:44:56

0

這是不可能的,你可能不需要它。試試這個:

context.save() // Save current state (includes transformations) 
context.rotate() 
... draw image ... 
context.restore() // Restore state 
+0

有縮放圖像,以類似的方式? – Kantesh 2011-07-01 09:21:54

3

當您在畫布上應用轉換時,您不會旋轉畫布。你只是告訴你所有你將要畫的東西都會以特定的方式轉變。如果要避免轉換影響其他命令,請使用save()restore()方法。它們允許保存和恢復畫布的設置。

ctx.save(); 
ctx.rotate(30); 
ctx.drawImage(); 
ctx.restore(); 
+0

有沒有類似的方式來縮放圖像? – Kantesh 2011-07-01 09:21:30

+0

是的,'scale'而不是'rotate'。還有兩個參數,水平和垂直縮放因子。 – bjornd 2011-07-01 09:42:00

1

我已經upvoted @ PeterT--偉大的片段和運作良好 - 謝謝你!我必須做出3個小改變才能使它適用於我:

1.寬度和高度的最大值不夠:如果考慮旋轉正方形,則需要一個直徑爲對角線的圓的廣場(var diam)。
2.畫布需要翻回(或使用保存/恢復)。
3.對象的x和y座標必須根據畫布大小進行調整。

所以我結束了:

rotateAndCache = function(image,angle) { 
     var offscreenCanvas = document.createElement('canvas'); 
     var offscreenCtx = offscreenCanvas.getContext('2d'); 

     var size = Math.max(image.width, image.height); 
     var diam = 2*((size/2)*Math.sqrt(2));     // needs to be saved 
     offscreenCanvas.width = diam; 
     offscreenCanvas.height = diam; 

     offscreenCtx.translate(diam/2, diam/2); 
     offscreenCtx.rotate(angle); 
     offscreenCtx.drawImage(image, -(image.width/2), -(image.height/2)); 
     offscreenCtx.translate(-diam/2, -diam/2); 

     return offscreenCanvas; 
} 


和調整戰平位置(需要保存在rotateAndCache):
mycontext.drawImage(rotobj,x-(diam-width)/2,y-(diam-height)/2);

+0

如果你想要精確,你需要一個直徑等於矩形對角線的圓,所以它應該是'var diam = Math.sqrt(image.width * image.width + image.height * image .height);'但是,我明白你的意思。 – PeterT 2014-10-17 22:50:40

+0

是的,最大的維度是混亂的,我的意思是對角線。代碼應該這樣做(它是一個1-1根-2直角三角形) – dhc 2014-10-17 22:54:46

+0

但是,這是一個長度爲'max(image.width,image.height)'的長方形的對角線,不是嗎?它可能會或可能不會略大於邊長不等的矩形(至少不會更小,因此不會導致錯誤)。 – PeterT 2014-10-17 22:56:40