问题
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