canvas繪製旋轉一定角度的矩形效果

admin發表於2017-02-17
分享一段程式碼例項,它實現了旋轉一定角度的矩形效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
var c = document.getElementById("myCanvas");
var context = c.getContext("2d");
//繪製黑色矩形
context.fillStyle = "black";
context.fillRect(20, 20, 25, 25);
 
 
context.setTransform(1, 0, 0, 1, 0, 0);
var angleInRadians = 45 * Math.PI / 180;
var x = 100;
var y = 100;
var width = 50;
var height = 50;
context.translate(x + .5 * width, y + .5 * height); //改變原點
 
context.rotate(angleInRadians); //旋轉角度
context.fillStyle = "red";
context.fillRect(-.5 * width, -.5 * height, width, height);
</script>
</body>
</html>

相關文章