简体   繁体   English

如何在组件中使用带有 Vue 的画布?

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

I'm tyring to add canvas to my Vue component this way, but it isn't work.我很想以这种方式将画布添加到我的 Vue 组件中,但它不起作用。

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.我尝试使用<canvas id="canvas"></canvas>来获取 canvas document.getElementById("canvas")但它也不起作用。

How to use canvas in Vue component ?如何在 Vue 组件中使用画布

<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:或者简单地将您的图像移动到public文件夹中,然后:

bg.src = "/bg.png";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM