vue+canvas第一次加载不显示

问题遇到的现象和发生背景

想使用vue+canvas,但是使用canvas后,第一次加载不显示,要刷新以后才显示。

用代码块功能插入代码,请勿粘贴截图
<template>
    <div id="app">
        <canvas id="mycanvas" width="500" height="500">canvas>
    div>
template>
 
<script>
    export default {
        name: 'cvs',
        mounted() {
            this.draw();
            
        },
        methods: {
            draw() {
                window.onload = function() {
                    var c = document.getElementById("mycanvas");
                    var ctx = c.getContext("2d");
                    ctx.beginPath();
                    // ctx.moveTo(50,150);
                    // ctx.lineTo(350,150);
                    // ctx.strokeStyle = 'green';
                    // ctx.lineWidth = 5;
                    ctx.fillRect(100,200,300,400)
                    ctx.stroke();
                    ctx.closePath();
                };
            }
        }
    }
script>
 
<style>
style>

运行结果及报错内容

第一次加载

img


刷新后

img

mounted后dom已经渲染到浏览器,不需要再window.onload


    export default {
        name: 'cvs',
        mounted() {
            this.draw();

        },
        methods: {
            draw() {
                //window.onload = function() {
                    var c = document.getElementById("mycanvas");
                    var ctx = c.getContext("2d");
                    ctx.beginPath();
                    // ctx.moveTo(50,150);
                    // ctx.lineTo(350,150);
                    // ctx.strokeStyle = 'green';
                    // ctx.lineWidth = 5;
                    ctx.fillRect(100,200,300,400)
                    ctx.stroke();
                    ctx.closePath();
               // };
            }
        }
    }

draw里window.onload 去掉试试

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632