Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use canvas with Vue in component? [closed]

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. Result of code

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>
like image 896
AlexIdest Avatar asked Nov 30 '25 03:11

AlexIdest


1 Answers

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";
like image 76
Fab Avatar answered Dec 02 '25 17:12

Fab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!