html5写一个动态玫瑰
时间: 2023-07-07 09:02:32 浏览: 62
编写HTML5动态玫瑰可以使用Canvas元素和JavaScript来实现。下面是一个简单的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<style>
canvas {
border: 1px solid #000;
margin-top: 20px;
}
</style>
</head>
<body>
<canvas id="rose" width="300" height="300"></canvas>
<script>
const canvas = document.getElementById("rose");
const context = canvas.getContext("2d");
let angle = 0;
function drawRose() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(canvas.width / 2, canvas.height / 2);
for (let i = 0; i < 360; i++) {
const radius = 100 * Math.sin(6 * i * (Math.PI / 180)); // 定义正弦函数的半径
const x = radius * Math.cos(i * (Math.PI / 180)); // 定义x坐标
const y = radius * Math.sin(i * (Math.PI / 180)); // 定义y坐标
context.beginPath();
context.arc(x, y, 1, 0, 2 * Math.PI);
context.fillStyle = `rgb(${i}, ${angle}, ${angle})`; // 根据角度改变颜色
context.fill();
}
context.translate(-canvas.width / 2, -canvas.height / 2);
angle = (angle + 1) % 255; // 改变角度
requestAnimationFrame(drawRose);
}
drawRose();
</script>
</body>
</html>
```
在上面的代码中,我们首先通过Canvas和JavaScript创建一个动态玫瑰的画布。然后使用translate()函数将坐标系平移到画布的中心。接下来,在一个循环中,我们使用正弦函数计算每个点的半径,以实现玫瑰的形状。我们还将根据角度的变化来改变颜色。最后,我们使用requestAnimationFrame()函数来循环绘制动态效果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)