今天在繪制一個足球滾動的時候,想使用rotate方法,之前看到這個方法的時候,並沒有引起任何重視,無非就是和CSS3里的rotate一樣的用么...
遺憾的是,事實並非如此,由於代碼在公司,我也就不去找那些圖片資源了,直接用一個黑色方塊代替
代碼如下:
var oCan = document.getElementById("canvas"); var ctx = oCan.getContext("2d"); ctx.rotate(30 * Math.PI / 180); ctx.fillRect(50,50,100,100);
顯示結果如下:
這...不能忍....於是乎打開了我心愛的w3school,發現一句有用的也沒多說(心寒)
下班后一路琢磨這個問題,終於想到,translate似乎可以改變坐標系的0,0點.
恩,這應該有用,但是...試了幾次,都失敗了,百度搜了幾篇文章,真的好廢柴,都是錯誤的,繼續搜,看到了一個老外寫的(還得是老外)
var x = 10; var y = 10; var width = 100; var height = 100 var cx = x + 0.5 * width; // x of shape center var cy = y + 0.5 * height; // y of shape center context.fillStyle = "#ff0000"; context.fillRect(x, y, width, height); //draw normal shape context.translate(cx, cy); //translate to center of shape context.rotate( (Math.PI / 180) * 25); //rotate 25 degrees. context.translate(-cx, -cy); //translate center back to 0,0 context.fillStyle = "#0000ff"; context.fillRect(x, y, width, height);
鏈接:http://tutorials.jenkov.com/html5-canvas/transformation.html#rotation
這次,恍然大悟,正解!封裝下吧,以后就用它了
function fillRotateRect(context,x,y,width,height,degrees){ var cx = x + 0.5 * width; var cy = y + 0.5 * height; context.translate(cx, cy); context.rotate( (Math.PI / 180) * degrees); context.translate(-cx, -cy); context.fillRect(x,y,width,height); }
但這個方法只能繪制正方形,遇到圖片,或者圓形,就又得改動,有時間了再思考怎么封裝一個比較妥善的吧.先到這里了