如何在Vue Konva中使用Sprite对象/动画?

现场

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

纯konva.js中,以这种方式创建Sprite对象-简而言之,首先创建Image对象,然后在Image对象的onload回调中创建Sprite对象。

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中,可以直接在文件<template>部分中将Konva对象创建为组件.vue,如下所示:

<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. 如果是这样,应该如何正确地为对象提供必要的image属性configSprite
  3. 如何控制v-sprite(开始/停止)的动画
  4. 如果使用v-sprite组件无法完成所有这些操作,是否可以手动创建Sprite对象并将其添加到必要的对象中v-layer

谢谢!

薰衣草

Sprite组件与v-imageComponent非常相似您可以看一下图像演示:https : //konvajs.github.io/docs/vue/Images.html

要启动/暂停精灵,您必须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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章