[英]Javascript ES6 HTML5 canvas images not drawing to background canvas or background canvas not showing
Images are not drawing to bg_canvas with a z-index of 0, only my main game canvas overlay is showing, i have only included the start of the code. 图像未绘制到z-index为0的bg_canvas上,仅显示了我的主游戏画布叠加层,而我仅包含了代码的开头。
// HTML
<canvas id="bg-canvas" width="768" height="600"></canvas>
<canvas id="canvas" width="768" height="600"></canvas>
// CSS
canvas {
position: absolute;
top: 0;
left: 0;
}
#canvas {
z-index: 1
}
#bg-canvas {
z-index: 0
}
// Javascript
const bg_canvas = document.getElementById('bg-canvas');
const bg_ctx = bg_canvas.getContext("2d");
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const map = {
object: {
brickwall: new Image(),
woodenbox: new Image()
}
};
map.object.brickwall.src = "objects/brickwall.jpeg";
map.object.woodenbox.src = "objects/boximage.jpg";
ctx.clearRect(0,0,canvas.width,canvas.height);
bg_ctx.clearRect(0,0,bg_canvas.width,bg_canvas.height);
// var currentItemEquipped;
// drawImage(imgsrc, xcoord, ycoord, sizex, sizey) // drawImage parameters
map.object.brickwall.onload = () => bg_ctx.drawImage(map.object.brickwall, 100, 100, 100, 100);
map.object.woodenbox.onload = () => bg_ctx.drawImage(map.object.woodenbox, 200, 200, 100, 100);
The player is drawing and the rest of the code is working completely fine however, i am not able to draw these images to the canvas, it may be a problem with z-indexes or that the overlaying canvas is not transparent. 播放器正在绘制,其余代码工作正常,但是,我无法将这些图像绘制到画布上,这可能是z索引存在问题,或者覆盖的画布不透明。
Have you tried "window.addEventListener" ? 您是否尝试过“ window.addEventListener”?
Because sometimes i got the same issue in some browsers... 因为有时候我在某些浏览器中遇到同样的问题...
try this: 尝试这个:
function LoadImages(){ bg_ctx.drawImage(map.object.brickwall, 100, 100, 100, 100); bg_ctx.drawImage(map.object.woodenbox, 200, 200, 100, 100); } window.addEventListener("load", LoadImages);
不得不在draw方法中调用该函数,但是由于背景画布从未被清除,所以不确定为什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.