I'm tyring to add canvas to my Vue component this way, but it isn't work.
Result of code on screenshot. There is no erros and warnings in console.

I tried to do get canvas document.getElementById("canvas") with <canvas id="canvas"></canvas> and it dosn't work too.
How to use canvas in Vue component?
<template>
<div>
<canvas
ref="canvas"
></canvas>
</div>
</template>
<script>
export default {
name: 'levelOne',
data: () => ({
}),
methods:{
func(){
let cvn = this.$refs.canvas;
let ctx = cvn.getContext("2d");
let bg = new Image();
bg.src = "../assets/bg.png";
bg.onload = function() {
ctx.drawImage(bg, 0 ,0);
};
}
},
mounted(){
this.func();
}
}
</script>
You can try in this way:
<script>
import myImage from "./assets/bg.png";
export default {
name: 'levelOne',
data: () => ({
}),
methods:{
func(){
let cvn = this.$refs.canvas;
let ctx = cvn.getContext("2d");
let bg = new Image();
bg.src = myImage;
bg.onload = function() {
ctx.drawImage(bg, 0 ,0);
};
}
},
mounted(){
this.func();
}
}
</script>
or simply move your image within the public folder and then:
bg.src = "/bg.png";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With