好家伙, 現在,我想要把我的飛機大戰塞到我的主頁里去,想辦法把文件導入 然後,直接死在第一步,圖片渲染都成問題 先用vue寫一個測試文件 來測試canvas的繪製 <template> <div> <div ref="stage"></div> <button @click="drawsth()"> ...
好家伙,
現在,我想要把我的飛機大戰塞到我的主頁里去,想辦法把文件導入
然後,直接死在第一步,圖片渲染都成問題
先用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>
搞定:
搞定了