3

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>
4
  • To clarify... Did you try getElemetById or getElementById? There's a small typo Commented Jan 7, 2020 at 17:02
  • @byxor I'm sorry, this is a typo only in question. I tried getElementById Commented Jan 7, 2020 at 17:05
  • Perhaps you're fetching the canvas successfully, but the image isn't loading. Can you render other things on the canvas, like text? e.g. ctx.font = '48px serif'; ctx.fillText('Hello world', 10, 50); Commented Jan 7, 2020 at 17:09
  • @byxor, yes it's work for text, but where is a problem if path to .png is correct? Commented Jan 7, 2020 at 17:12

1 Answer 1

3

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";
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it works! But moving bg.png to the same folder stiil dosn't. You know why? This is very strange
do you mean the public folder? However, here you can find more informations: cli.vuejs.org/guide/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.