vue使用时必须在mounted
里面、或者点击触发,因为在这个生命周期后才能获取dom
元素
vue代码
<template> <div><canvas id="myCanvas" width="800" height="800"></canvas></div> </template> <script> //导入 axios 用于获取接口数据用的 import axios from "axios"; export default { data() { return { }; }, methods: { }, created() { axios({ //写接口路径用 url: "", //请求方式 method: "", //用于传参 params: { }, }) .then((res) => { //接口拿来的数据用变量 imgbase64=接口数据 var imgbase64 = res.data; let img = new Image(); img.src = imgbase64; let myCanvas = document.getElementById("myCanvas").getContext("2d"); img.onload = () => { myCanvas.drawImage(img, 90, 250, 180, 240); myCanvas.font = "25px Arial"; myCanvas.fillText("邀请码", 140, 190, 100, 0); }; }) .catch((err) => { console.log(err); }); }, }; </script>