我有一个Paper实例,该实例带有一个工具,该工具可以在mouseMove上绘制路径,并且如果段数大于50,则在该路径的开头删除这些段。到目前为止,一切工作正常。这是代码:
<template>
<div>
<canvas id="canvas" resize></canvas>
</div>
</template>
<script>
import paper from 'paper';
export default {
name: 'home',
components: {
},
created() {
paper.install(window);
},
mounted() {
const canvas = this.$el.querySelector('#canvas');
paper.setup(canvas);
const path = new Path();
path.strokeColor = '#f5bb56';
path.strokeWidth = 2;
this.tool = new Tool()
this.tool.onMouseMove = event => {
if (path.segments.length > 50) {
path.removeSegment(0)
};
path.add(event.point);
path.smooth({
type: 'continuous'
});
};
view.draw()
},
};
</script>
<style lang="scss">
#canvas {
width: 100%;
height: 100%;
}
</style>
问题在于,现在我要开始以50毫秒的间隔从该路径中删除段,但是在添加新段时停止执行该段。我正在寻找一些东西来在事件未触发约两秒钟时将其设置为timeout(()=> {eraseFunction()})。
我在mouseMove事件开始时添加了一个指向包含它的变量的clearTimeout,并在结尾处对其进行了设置,因此,如果正在运行超时,我将在mouseMove启动时将其删除:
export default {
name: 'home',
components: {
},
data() {
return {
tool: null,
path: null,
erase: null,
}
},
created() {
paper.install(window);
},
mounted() {
const canvas = this.$el.querySelector('#canvas');
paper.setup(canvas);
this.path = new Path();
this.path.strokeColor = '#f5bb56';
this.path.strokeWidth = 2;
this.tool = new Tool()
this.tool.onMouseMove = event => {
clearTimeout(this.erase);
if (this.path.segments.length > 50) {
this.path.removeSegment(0)
};
this.path.add(event.point);
this.path.smooth({
type: 'continuous'
});
this.erase = setTimeout(() => {
this.eraseFunction()
}, 2000);
};
view.draw()
},
methods: {
eraseFunction() {
setInterval(() => {
this.path.removeSegment(0);
}, 500);
}
}
};
</script>
问题在于超时并没有消除,并且给定了一定的时间,我无法绘制新的细分,因为它们是被立即删除的。
答案 0 :(得分:1)
您还需要清除 setInterval 。您只清除setTimeout。 setInterval仍在运行删除段。
答案 1 :(得分:1)
ClearInterval需要您要清除的intervalID。 intervalID是通过setInterval调用给出的。
您应该在deleteFunction中返回setTimout调用的结果:
eraseFunction() {
return setInterval(() => {
this.path.removeSegment(0);
}, 500);
}
然后应将其分配给此方法。擦除EraseFunction调用的结果,而不是setTimeout:
setTimeout(() => {
this.erase = this.eraseFunction()
}, 2000);