如何在 Vue Konva 中使用 Sprite objects/animations?

How to use Sprite objects/animations in Vue Konva?

我正在尝试使用 konva.js(利用 vue-konva)在 Vue 中创建 spritesheet 动画。

pure konva.js中,创建了Sprite对象this way——简而言之,先创建Image对象,再创建Sprite对象在 Image 对象的 onload 回调中创建。

var imageObj = new Image();
imageObj.onload = function() {
  var blob = new Konva.Sprite({
    x: 50,
    y: 50,
    image: imageObj,
    animation: 'idle',
    animations: animations, // object defined earlier
    frameRate: 7,
    frameIndex: 0
  });

  // add the shape to the layer
  layer.add(blob);

  // add the layer to the stage
  stage.add(layer);

  // start sprite animation
  blob.start();
};
imageObj.src = '/assets/blob-sprite.png';

另一方面,在 vue-konva 中,可以直接在 .vue 文件的 <template> 部分中将 Konva 对象创建为组件,像这样:

<template>
  <v-stage :config="configKonva">
    <v-layer>
      <v-circle :config="configCircle"></v-circle>
    </v-layer>
  </v-stage>
</template>

我的问题是:

  1. 是否可以创建 <v-sprite :config="configSprite"></v-sprite> 组件?文档中没有提到这一点。
  2. 如果是这样,应该如何正确地为 configSprite 对象提供必要的 image 属性?
  3. 如何控制 v-sprite (starting/stopping) 的动画?
  4. 如果使用 v-sprite 组件无法实现所有这些,是否可以以某种方式手动创建 Sprite 对象并将其添加到必要的 v-layer

谢谢!

精灵组件与v-image组件非常相似。您可以查看图像演示:https://konvajs.github.io/docs/vue/Images.html

对于 start/pause 精灵,您必须访问原生 Konva 对象并手动控制动画。您可以使用参考文献来做到这一点:

<template>
  <v-stage ref="stage" :config="stageSize">
    <v-layer ref="layer">
      <v-sprite
        @click="handleClick"
        ref="sprite"
        :config="{
          image: image,
          animation: 'idle',
          animations: animations,
          frameRate: 7,
          frameIndex: 0,
          animations: {
            idle: [
              2,
              2,
              70,
              119,
              71,
              2,
              74,
              119,
              146,
              2,
              81,
              119,
              226,
              2,
              76,
              119
            ],
            punch: [2, 138, 74, 122, 76, 138, 84, 122, 346, 138, 120, 122]
          }
        }"
      />
    </v-layer>
  </v-stage>
</template>

<script>
const width = window.innerWidth;
const height = window.innerHeight;

export default {
  data() {
    return {
      stageSize: {
        width: width,
        height: height
      },
      image: null
    };
  },
  created() {
    const image = new window.Image();
    image.src = "https://konvajs.github.io/assets/blob-sprite.png";
    image.onload = () => {
      // set image only when it is loaded
      this.image = image;
    };
  },
  methods: {
    handleClick() {
      const node = this.$refs.sprite.getNode();
      if (node.isRunning()) {
        node.stop();
      } else {
        node.start();
      }
    }
  }
};
</script>

在线演示:https://codesandbox.io/s/lxlqzok2m9