canvas入门学习(二)-简单图形绘制

以下是利用canvas绘制的简单图形:线段,矩形,三角形,五角星,仅供小白参考。

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>利用canvas绘制基本图形</title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
			}
			
			.wrapper {
				margin: auto;
				border: 3px solid gold;
				width: 1216px;
				padding: 10px;
			}
			
			canvas {
				border: 1px solid blueviolet;
			}
		</style>
	</head>

	<body>
		<div class="wrapper">
			<!--画线段1-->
			<canvas id="canvas1" width="400" height="400"></canvas>
			<!--画矩形2-->
			<canvas id="canvas2" width="400" height="400"></canvas>
			<!--画三角形3-->
			<canvas id="canvas3" width="400" height="400"></canvas>
			<!--画矩形4-->
			<canvas id="canvas4" width="400" height="400"></canvas>
			<!--画弧线-->
			<canvas id="canvas5" width="400" height="400"></canvas>
			<!--画五角星-->
			<canvas id="canvas6" width="400" height="400"></canvas>
		</div>
	</body>

</html>
<script type="text/javascript">
	// 画线段
	var ctx = document.getElementById("canvas1").getContext("2d");
	ctx.beginPath();
	ctx.moveTo(200, 100);
	ctx.lineTo(200, 300);
	ctx.strokeStyle = "red";
	ctx.lineWidth = 10;
	ctx.lineCap = "round";
	ctx.stroke();

	// 画矩形(利用线段)
	var ctx2 = document.getElementById("canvas2").getContext("2d");
	ctx2.beginPath();
	ctx2.moveTo(100, 100);
	ctx2.lineTo(100, 300);
	ctx2.lineTo(300, 300);
	ctx2.lineTo(300, 100);
	ctx2.strokeStyle = "blueviolet";
	ctx2.lineWidth = 10;
	ctx2.lineCap = "round";
	ctx2.closePath();
	ctx2.stroke();

	// 画三角形
	var ctx3 = document.getElementById("canvas3").getContext("2d");
	ctx3.beginPath();
	ctx3.moveTo(100, 100);
	ctx3.lineTo(100, 300);
	ctx3.lineTo(300, 300);
	ctx3.strokeStyle = "darkcyan";
	ctx3.lineWidth = 10;
	ctx3.lineCap = "square";
	ctx3.closePath();
	ctx3.stroke();
	ctx3.fillStyle = "gray";
	ctx3.fill();

	// 直接画矩形(内部颜色填充)
	var ctx4 = document.getElementById("canvas4").getContext("2d");
	ctx4.fillStyle = "#00ff00";
	ctx4.fillRect(50, 50, 300, 300);

	// 画弧线
	var ctx5 = document.getElementById("canvas5").getContext("2d");
	ctx5.beginPath();
	ctx5.arc(200, 200, 100, 0, 1.5 * Math.PI, false);
	ctx5.lineWidth = 5;
	ctx5.strokeStyle = "#005";
	ctx5.stroke();
	ctx5.closePath();
	ctx5.fillStyle="red";
	ctx5.fill();
	
	// 画五角星
	var ctx6 = document.getElementById("canvas6").getContext("2d");
	ctx6.beginPath();
    for (var i = 0; i < 5; i++) {
        ctx6.lineTo(Math.cos((18+i*72)/180*Math.PI)*200+200,
                        -Math.sin((18+i*72)/180*Math.PI)*200+200);
        ctx6.lineTo(Math.cos((54+i*72)/180*Math.PI)*80+200,
                        -Math.sin((54+i*72)/180*Math.PI)*80+200);
    }
    ctx6.closePath();
    ctx6.lineWidth=5;
    ctx6.fillStyle = "darkcyan";
    ctx6.strokeStyle = "blue";
    ctx6.fill();
    ctx6.stroke();
</script>

效果图:




猜你喜欢

转载自blog.csdn.net/qq_41115965/article/details/80299263