赞
踩
为了使用HTML写一个烟花效果,您可以使用以下代码:
- <!DOCTYPE html>
- <html>
- <head>
- <style>
- canvas {
- display: block;
- background: black;
- }
- </style>
- </head>
- <body>
-
- <canvas id="myCanvas" width="400" height="400"></canvas>
-
- <script>
- //获取canvas元素
- var canvas = document.getElementById("myCanvas");
- //获取绘图上下文
- var ctx = canvas.getContext("2d");
-
- var colors = ["red", "orange", "yellow", "green", "blue", "purple"];
-
- function draw() {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
-
- //画随机的烟花
- for (var i = 0; i < 100; i++) {
- var x = Math.random() * canvas.width;
- var y = Math.random() * canvas.height;
- var radius = Math.random() * 20 + 10;
- var color = colors[Math.floor(Math.random() * colors.length)];
-
- drawFirework(x, y, radius, color);
- }
-
- //重复执行动画
- requestAnimationFrame(draw);
- }
-
- function drawFirework(x, y, radius, color) {
- //画圆
- ctx.beginPath();
- ctx.arc(x, y, radius, 0, 2 * Math.PI);
- ctx.fillStyle = color;
- ctx.fill();
- }
-
- draw();
- </script>
-
- </body>
- </html>
这个代码将会在一个黑色的画布上绘制100个随机的烟花,每个烟花都有随机的颜色和半径。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。