• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

43
Views
Can you copy only a specific area from one Canvas to another?

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?

about 2 months ago ·

Juan Pablo Isaza

2 answers
Answer question

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>

about 2 months ago · Juan Pablo Isaza Report

0

getImageData(sx, sy, sw, sh)

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)
about 2 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.