I added two canvases on a single div element, canvases has position absolute and parent div has position relative, I can see one canvas is on top of another, but the top canvas hides the bottom canvas, i thought canvases were transparent by default. Even though I don't draw anything to the top canvas and just call clearRect on its 2d rendering context
if I increase z index of bottom canvas wouldn't that hide the top canvas now
changing the z index doesn't make both canvases visible, it only makes the higher z index visible
I need to display text on top of an existing canvas, i am making a 2d canvas game how do I achieve that
No my main canvas has a lower resolution that the gameplay is drawn. I have another canvas with higher resolution for drawing text
<canvas id="gameplay-canvas" width="400" height="300"></canvas>
<canvas id="text-canvas" width="800" height="600"></canvas>
<style>
#gameplay-canvas, #text-canvas {
position: absolute;
top: 0;
left: 0;
}
</style>
I have this exact code, but the top canvas that displays the text hides the bottom canvas with lower resolution
Edit
Here's the full index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link href="#" rel="icon">
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<title>Blue Retro JS2023</title>
<style>* { background: #444444; padding: 0; margin: 0; }
body #app-wrap { display: flex; justify-content: center; align-items: center; }
#app {
position: relative;
width: min(99vw, calc(99vh * 16/9));
aspect-ratio: 16/9;
cursor: pointer;
}
#app canvas {
position: absolute;
top: 0;left: 0;
width: 100%;
height: 100%;
background-color: transparent;
}
#app canvas.pixelated { image-rendering: pixelated;}
</style>
</head>
<body><div id='app-wrap'><div id="app"></div></div><script type="module" src="/src/main.ts"></script></body>
</html>
I add two canvases like this:
static make = (width: number, height: number, pixelated = true) => {
let canvas = document.createElement('canvas')
if (pixelated) {
canvas.classList.add('pixelated')
}
let ctx = canvas.getContext('2d')!
const on_resize = () => {
canvas.width = width
canvas.height = height
ctx.imageSmoothingEnabled = pixelated
}
document.addEventListener('scroll', on_resize, { capture: true, passive: true })
window.addEventListener('resize', on_resize, { passive: true })
on_resize()
return new Graphics(canvas, ctx)
}
class Graphics {
constructor(readonly canvas: HTMLCanvasElement) {}
}
// somewhere else
element.appendChild(graphics.canvas)
element.appendChild(texts.canvas)