javascript - 当 tool.mouseMove 事件开始时清除超时(PaperJs、VueJs)

标签 javascript vue.js timeout paperjs

我有一个带有工具的 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 毫秒的间隔从该路径删除段,但在添加新段时停止执行。我正在寻找一些东西来将变量设置为超时(()=> {eraseFunction()}),当事件在大约两秒内没有触发时。

我添加了一个clearTimeout,指向在mouseMove事件开始时包含它的变量,并在结束时设置它,所以如果有超时运行,我会在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>

问题是超时没有被删除,并且在一定的时间内,我无法绘制新的段,因为它们会立即被删除。

最佳答案

您还需要清除setInterval。您只是清除 setTimeout。 setInterval 仍在运行并删除您的分段。

关于javascript - 当 tool.mouseMove 事件开始时清除超时(PaperJs、VueJs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55269462/

相关文章:

javascript - 如何在 Vue 中的方法函数之前设置变量(去抖)?

javascript - vue.js - 如何将对象数组拆分为多个 div 列

timeout - GitLab CI 管道阶段超时

linux - 非阻塞套接字客户端连接

javascript - Ajax 改变滚动位置

javascript - Angular 服务给出 "TypeError: Cannot read property ' helloConsole' 未定义”

Vue.js 问题 : Prop doesn't change image v-bind:src

java - 如何在1.8中使用可调用的futuretask完全杀死正在执行的任务

javascript - 需要 android webview 的帮助

javascript - ExtJS 6 - 隐藏组件时停止事件委托(delegate)?