1. 程式人生 > >canvas畫布變換畫六芒星

canvas畫布變換畫六芒星

要求使用canvas的畫布變換方法。

效果如下:


程式碼如下:

<!DOCTYPE html>
<html>
<head>
	<title>六芒星</title>
	<meta charset="utf-8">
</head>
<body>
	<canvas id="canvas" width="220" height="220"></canvas>

	<script type="text/javascript">
		var canvas = document.querySelector('#canvas'),
			context = canvas.getContext('2d');

		var width = canvas.width,
			height = canvas.height;

		// 原點座標
		var originX = width / 2,
			originY = height / 2,
			radius = 100;

		context.lineWidth = 1;

		// 畫外圈
		context.strokeStyle = '#000';
		context.beginPath();
		context.arc(originX, originY, radius, 0, 2 * Math.PI);
		context.stroke();
		context.closePath();

		context.beginPath();
		context.arc(originX, originY, radius + 10, 0, 2 * Math.PI);
		context.stroke();
		context.closePath();

		// 把原點移動到圓心,旋轉之後才不會變形
		context.translate(originX, originY)
		for (var i = 0; i < 6; i++) {
			// 畫完三角形後旋轉一半形度畫另一個三角形
			if (i === 3) {
				context.rotate(Math.PI * 2 / 6);
			}
			context.moveTo(0, -radius);
			context.lineTo(radius * Math.sin(Math.PI / 3), radius / 2);
			context.stroke();
			context.rotate(Math.PI * 2 / 3);
		}
	</script>
</body>
</html>