我的第一个项目(七):(解决问题)Vue中canvas无法绘制图片
好家伙,
现在,我想要把我的飞机大战塞到我的主页里去,想办法把文件导入
然后,直接死在第一步,图片渲染都成问题
先用vue写一个测试文件
来测试canvas的绘制
<template>
<div>
<div ref="stage"></div>
<button @click="drawsth()">添加</button>
<img src="../assets/logo.png" alt="">
</div>
</template>
<script>
// import { PlaneBattle } from "../../../../PB for Vue/startgame"
// console.log(document.getElementById('stage'))
// plane.create(document.getElementById('stage'));
export default {
methods: {
drawsth() {
// PlaneBattle.createNewGame(this.$refs.stage)
// console.log(this.$refs.stage)
// plane.create(this.$refs.stage)
console.log("我被执行啦")
let canvas = document.createElement('canvas');
this.$refs.stage.appendChild(canvas);
canvas.width = 480;
canvas.height = 650;
canvas.ref = canvas;
canvas.style = "border: 1px solid red;"
// this.$ref.stage.style =
console.log(this.$refs.stage)
console.log("...")
console.log(this.$refs.stage.canvas)
const context = canvas.getContext("2d");
let img = new Image();
img.src = "../assets/logo.png";
context.drawImage(img, 0, 0 ,480 ,650)
}
}
}
</script>
<style>
#stage {
width: 480px;
height: 650px;
margin: 0 auto;
}
</style>
随后,在大佬的帮助下,我找到了问题所在
问题一:
应使用require的方式设置图片的src
img.src = "../assets/logo.png";
改为:
img.src = require("../assets/logo.png")
问题二:
必须在图片加载完毕后再进行绘制
context.drawImage(img, 0, 0 ,480 ,650)
改为(在外面套一层onload)
img.onload = function () {
console.log("img加载完毕")
context.drawImage(img, 0, 0 ,480 ,650)
}
修改后的代码:
<template>
<div>
<div ref="stage"></div>
<button @click="drawsth()">添加</button>
<img src="../assets/logo.png" alt="">
</div>
</template>
<script>
// import { PlaneBattle } from "../../../../PB for Vue/startgame"
// console.log(document.getElementById('stage'))
// plane.create(document.getElementById('stage'));
export default {
methods: {
drawsth() {
// PlaneBattle.createNewGame(this.$refs.stage)
// console.log(this.$refs.stage)
// plane.create(this.$refs.stage)
console.log("我被执行啦")
let canvas = document.createElement('canvas');
this.$refs.stage.appendChild(canvas);
canvas.width = 480;
canvas.height = 650;
canvas.ref = canvas;
canvas.style = "border: 1px solid red;"
// this.$ref.stage.style =
console.log(this.$refs.stage)
console.log("...")
console.log(this.$refs.stage.canvas)
const context = canvas.getContext("2d");
let img = new Image();
// img.src = "../assets/logo.png";
img.src = require("../assets/logo.png")
img.onload = function () {
console.log("img加载完毕")
context.drawImage(img, 0, 0 ,480 ,650)
}
}
}
}
</script>
<style>
#stage {
width: 480px;
height: 650px;
margin: 0 auto;
}
</style>
搞定:
搞定了