彩虹小伞效果图如下:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>作业1</title>
<style> #canvas { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: 100px auto; } </style>
</head>
<body>
<canvas id="canvas" width="500" height="800"></canvas>
<script> var canvas = document.getElementById("canvas"); var pen = canvas.getContext("2d"); // 彩虹七色小伞 var rainbow = ["#FF0000","#FF7F00","#FFFF00","#00FF00","#00FFFF","#0000FF","#871F78"] for (var i = 0; i < 7; i++) { pen.fillStyle = pen.strokeStyle = rainbow[i]; // 伞盖 pen.beginPath(); pen.arc(30 + 70 * i, 140, 30, Math.PI, 2 * Math.PI); pen.closePath(); pen.fill(); // 伞柄 pen.beginPath(); pen.moveTo(30 + 70 * i, 140); pen.lineTo(30 + 70 * i, 187); pen.closePath(); pen.stroke(); // 伞把 pen.beginPath(); pen.arc(26 + 70 * i, 187, 4, 0, Math.PI); pen.stroke(); } // 随机变颜色的七个小伞 // setInterval(function () { // for (var i = 0; i < 7; i++) { // pen.fillStyle = pen.strokeStyle = randomColor(); // // 伞盖 // pen.beginPath(); // pen.arc(30 + 70 * i, 40, 30, Math.PI, 2 * Math.PI); // pen.closePath(); // pen.fill(); // // 伞柄 // pen.beginPath(); // pen.moveTo(30 + 70 * i, 40); // pen.lineTo(30 + 70 * i, 87); // pen.closePath(); // pen.stroke(); // // 伞把 // pen.beginPath(); // pen.arc(26 + 70 * i, 87, 4, 0, Math.PI); // pen.stroke(); // } // }, 1000) // 生成随机颜色的方法 function randomColor() { var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'] var c = '' for (var i = 0; i < 6; i++) { c += arr[Math.round(Math.random() * 15)] } return "#" + c; } </script>
</body>
</html>