[英]HTML5 rotating an image with canvas
如何使用畫布圍繞圖像中心的“旋轉”功能旋轉圖像,而不是圍繞原點旋轉。
請考慮以下示例:
<html>
<head></head>
<body>
<canvas id="tmp" style="width: 300px; height: 300px; border: 1px red solid" />
<script type="text/javascript">
var deg = 0;
function Draw() {
var ctx = document.getElementById('tmp').getContext('2d');
ctx.save();
ctx.fillStyle = "white";
ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.fillStyle = "red";
ctx.rotate(deg * 0.0174532925199432957); //Convert to rad's
ctx.fillRect(50, 50, 20, 20);
ctx.restore();
deg+=5;
setTimeout("Draw()", 50);
}
Draw();
</script>
</body>
</html>
在這個例子中,紅色方塊圍繞orgin旋轉0,0。 說我想圍繞它的中心旋轉方塊。 我已經嘗試使用translate將其移動到原點然后旋轉然后再次使用translate將其移回原樣:
ctx.translate(-(50 + 10), -(50 + 10)); //Move to origin
ctx.rotate(deg * 0.0174532925199432957); //rotate
ctx.translate(50, 50); //move back to original location
ctx.fillRect(50, 50, 20, 20);
ctx.restore();
但看起來對translate函數的調用會覆蓋先前的translate並且不會組合轉換。 那怎么能達到我想要的效果呢?
這是你在尋找什么: jsFiddle ?
//Move to center of rectangle
ctx.translate(60, 60);
ctx.rotate(deg * 0.0174532925199432957); //rotate
//Draw rectangle
ctx.fillRect(-10, -10, 20, 20);
ctx.restore();
請注意,您應該使用Math.PI/180
而不是大小數。
我還在畫布上正確設置了width
和height
,並將setTimeout
更改為不使用eval()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.