写一段js代码 生成心形动画
时间: 2023-05-10 15:55:15 浏览: 66
以下是一个简单的 JavaScript 代码,用于在 HTML5 canvas 中生成心形图案动画:
```html
<canvas id="myCanvas" width="400" height="400"></canvas>
```
```javascript
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const width = canvas.width;
const height = canvas.height;
let time = 0;
let animation;
function draw() {
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "red";
ctx.beginPath();
let x = 16 * Math.pow(Math.sin(time), 3);
let y =
13 * Math.cos(time) -
5 * Math.cos(2 * time) -
2 * Math.cos(3 * time) -
Math.cos(4 * time);
x = (x * width) / 30 + width / 2;
y = (y * height) / 30 + height / 2;
ctx.arc(x, y, 5, 0, 2 * Math.PI);
ctx.fill();
time += 0.05;
animation = requestAnimationFrame(draw);
}
animation = requestAnimationFrame(draw);
```
该代码使用了数学公式绘制心形曲线,随着时间的推移,通过改变曲线上的点的位置,可以创建一个心形图案动画。这段代码首先获取一个 HTML5 canvas 元素,并获取其上下文。然后,它在画布上绘制一个红色的小圆点,其位置由心形曲线计算而来。最后,它使用 requestAnimationFrame() 函数来递归调用 draw() 函数,从而创建一个连续的动画效果。