在 Vue Konva 中仅检测非透明像素的图像事件 (drawHitFromCache)

Detecting image events for non-transparent pixels only (drawHitFromCache) in Vue Konva

所以我基本上是在尝试重现 this behavior - 仅检测非透明像素的事件(如悬停在狮子上方时所见) - 但在 vue-konva.

Here is the demo我正在合作。它基本上只是加载狮子的图像并将鼠标事件附加到它。

根据文档,为了仅对非透明像素进行事件检测,我必须对狮子的图像对象调用方法 cache()drawHitFromCache()

在Vue中这两个方法应该在代码的什么时候调用?当我尝试在图像的 onload 回调中调用它们时(请参阅演示中注释的 行 46-47),我收到以下错误:

Konva error: Width or height of caching configuration equals 0. Caching is ignored.

Cannot read property 'scene' of undefined

谢谢!

Vue 可以异步更新组件的属性。因此,当您调用 cache() 时,您会看到 Caching is ignored 因为节点尚未更新,所以 Konva 没有关于其大小的信息。要解决此问题,您可以在 updated 生命周期方法(加载图像时)中调用 cache。或者您可以在下一个滴答时缓存节点:

image.onload = () => {
  // set image only when it is loaded
  this.configImage.image = image;

  this.$nextTick(() => {
    this.$refs.staticImage.getNode().cache();
    this.$refs.staticImage.getNode().drawHitFromCache();
  });
};