As of right now Im rendering a map once to an offscreen canvas, wich then gets copied to the main canvas every frame, so I dont have to re-render every object on my map every frame, wich gets really laggy, my offscreen canvas needs to be relativly large to fit the whole map tho and the whole canvas gets copied onto the normal canas every frame wich also isn't that performant, so my question is; is there any way to only copy a section of a canvas to another canvas, so I dont have to copy the whole thing?
Asked
Active
Viewed 260 times
0
-
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData allows you to extract image data based on a X/Y coordinate and a width & height, and https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData allows you to place it at a X/Y coordinate. – CBroe Jun 15 '22 at 06:47
2 Answers
0
You can drawImage
your canvas:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const offscreen = Object.assign(
document.createElement("canvas"),
{ width: 2500, height: 2500 }
);
makeNoise(offscreen.getContext("2d"));
canvas.onmousemove = evt => {
const x = evt.clientX - canvas.offsetLeft;
const y = evt.clientY - canvas.offsetTop;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(offscreen, x - offscreen.width / 2, y - offscreen.height / 2);
}
// fills a context with noise,
// we use it only to draw somehing on the offscreen canvas
function makeNoise(ctx) {
const img = new ImageData(ctx.canvas.width, ctx.canvas.height);
const data = new Uint32Array(img.data.buffer);
for (let i = 0; i<data.length; i++) {
data[i] = Math.random() * 0xFFFFFF + 0xFF000000;
}
ctx.putImageData(img, 0, 0);
}
Use your mouse to move the offscreen canvas<br>
<canvas><canvas>

Kaiido
- 123,334
- 13
- 219
- 285
-1
allows you to extract image data based on a X/Y coordinate and a width & height, and
putImageData(imageData, dx, dy)
allows you to place it at a X/Y coordinate.
Or use drawImage, that allows you to use the existing canvas as "input" directly, and you can specify X/Y and width/height for both the origin and the target:
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

CBroe
- 91,630
- 14
- 92
- 150