<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>这段代码有问题吗
时间: 2024-02-14 19:06:19 浏览: 82
这段代码中存在一个问题,即在 `animateHeart` 函数中,`this` 指向的不是组件实例,而是 `window` 对象。因此,需要将 `animateHeart` 函数改为箭头函数,或者使用 `bind` 方法将 `this` 绑定到组件实例上。具体的修改方法如下:
1. 箭头函数:
```javascript
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);
```
2. 使用 `bind` 方法:
```javascript
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.bind(this),
1000 / this.framesPerSecond
);
```
阅读全文