帮我生成一段前端代码 vue ,一个按钮点击后生成一段3秒的动态心形图片
时间: 2024-02-27 16:52:20 浏览: 100
好的,以下是一个Vue前端代码示例,点击按钮后生成一段3秒的动态心形图片:
```
<template>
<div>
<button @click="generateHeart">生成心形图片</button>
<canvas ref="canvas"></canvas>
</div>
</template>
<script>
export default {
data() {
return {
canvasWidth: 400,
canvasHeight: 400,
framesPerSecond: 30,
duration: 3000,
startTime: null,
timer: null,
};
},
methods: {
generateHeart() {
const canvas = this.$refs.canvas;
canvas.width = this.canvasWidth;
canvas.height = this.canvasHeight;
const context = canvas.getContext("2d");
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const stepSize = 0.1;
let x = 0;
let y = 0;
let t = 0;
context.beginPath();
context.moveTo(centerX + x, centerY + y);
function animateHeart() {
if (!this.startTime) {
this.startTime = Date.now();
}
const elapsed = Date.now() - this.startTime;
const progress = elapsed / this.duration;
if (progress > 1) {
clearInterval(this.timer);
this.startTime = null;
return;
}
t += stepSize;
x = 16 * Math.pow(Math.sin(t), 3);
y =
-(
13 * Math.cos(t) -
5 * Math.cos(2 * t) -
2 * Math.cos(3 * t) -
Math.cos(4 * t)
);
context.lineTo(centerX + x, centerY + y);
context.stroke();
}
this.timer = setInterval(() => {
animateHeart();
}, 1000 / this.framesPerSecond);
},
},
};
</script>
```
这段代码使用了 HTML 的 canvas 元素来绘制心形图案,并通过 setInterval 函数来实现动态效果。在点击按钮后,会调用 generateHeart 函数来生成心形图案,然后启动定时器,每次执行 animateHeart 函数来绘制心形图案的每一帧,直到动画结束。你可以根据自己的需要,调整 canvas 的大小、帧率和持续时间等参数,以及图案的绘制方式。
阅读全文