Vue.js Konva library to display a simple image, what am I missing?

半世苍凉 提交于 2019-12-18 07:07:39

问题


So I went through the sample code listed on the vue-konva page. Although it samples creating shapes I understood it enough to try to display a simple image to start. Here is the base code. My question lies in how do I attach the actual image file to the "image" property. Or if I am missing something else.

 <template>
  <div id="app">
    <h1>Display Image via Konva</h1>
    <div>
      <v-stage ref="stage" :config="configKonva">
        <v-layer ref="layer">
          <v-image :config="configImg"></v-image>
        </v-layer>
      </v-stage>
    </div>
  </div>
</template>

<script>
  import Vue from 'vue';
  import VueKonva from 'vue-konva'
  Vue.use(VueKonva)

export default {
  data() {
    return {
      testImg: new Image(),
      configKonva: {
        width: 500,
        height: 500
      },
      configImg: {
        x: 20,
        y: 20,
        image: this.testImg,
        width: 200,
        height: 200,
      },
    }
  }
</script>

According to the Konva Docs this is how to do it:

var imageObj = new Image();
imageObj.onload = function() {
  var image = new Konva.Image({
    x: 200,
    y: 50,
    image: imageObj,
    width: 100,
    height: 100
  });
};
imageObj.src = '/path/to/image.jpg'

Therefore I believe the issue lies in how I attach the actual image file to the image property.

I tried the all following:

#1
image: "/path/to/image.jpg"
#2
mounted(){
   this.testImg.src = "/path/to/image.jpg"
}
#3
data(){
  return{
    testImg: "/path/to/image.jpg"
    }
  }
}

nothing seems to work. I'm sure there is a step I am missing.


回答1:


The trick seems to be to make configImg reactive by putting it in a computed property, since the image will load after mounting.

export default {
  data() {
    return {
      testImg: new Image(100, 100),
      configKonva: {
        width: 200,
        height: 200
      }
    }
  },
  computed: {
    configImg: function() {
      return {
        x: 20,
        y: 20,
        image: this.testImg,
        width: 200,
        height: 200,
      }
    }
  },
  mounted() {
    this.testImg.src = "https://konvajs.github.io/assets/lion.png"
  }
}   



回答2:


  mounted() {
    this.testImg.onload = () => this.$refs.layerImg.getStage().draw()
    this.testImg.src = "https://konvajs.github.io/assets/lion.png"
  }


来源:https://stackoverflow.com/questions/48588800/vue-js-konva-library-to-display-a-simple-image-what-am-i-missing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!