7

I am trying to copy the contents of one canvas to another.

The source canvas has a webgl context.

The destination canvas has a 2d context.

My code looks like:

destinationContext.drawImage(sourceCanvas, 0, 0);

This works in Firefox and IE, but it does not work in Chrome. Why not?

Thanks!

Dave Brown
  • 83
  • 1
  • 4

1 Answers1

3

Here's some working code.

const gl = document.querySelector("#a").getContext("webgl");
const ctx = document.querySelector("#b").getContext("2d");

// put a rectangle in the webgl canvas
gl.enable(gl.SCISSOR_TEST);
gl.scissor(10,20,100,50);
gl.clearColor(0,0,1,1);
gl.clear(gl.COLOR_BUFFER_BIT);

// copy the webgl canvas to the 2d canvas
ctx.drawImage(gl.canvas, 0, 0);
canvas {
  border: 1px solid black;
  margin: 5px;
}
<canvas id="a" width="200" height="100"></canvas>
<canvas id="b" width="200" height="100"></canvas>

Here's some working code with a delay. If you are not copying the WebGL canvas in the same event that you drew to it then you need one of these solutions. Even though that question is about toDataURL all the same things apply to using a WebGL canvas with drawImage.

const gl = document.querySelector("#a").getContext("webgl", {
  preserveDrawingBuffer: true,
});
const ctx = document.querySelector("#b").getContext("2d");

// put a rectangle in the webgl canvas
gl.enable(gl.SCISSOR_TEST);
gl.scissor(10,20,100,50);
gl.clearColor(0,0,1,1);
gl.clear(gl.COLOR_BUFFER_BIT);

// copy the webgl canvas to the 2d canvas 1 second later
setTimeout(copy, 1000);

function copy() {
  ctx.drawImage(gl.canvas, 0, 0);
}
canvas {
  border: 1px solid black;
  margin: 5px;
}
<canvas id="a" width="200" height="100"></canvas>
<canvas id="b" width="200" height="100"></canvas>
gman
  • 100,619
  • 31
  • 269
  • 393
  • I am having a very similar problem as the one your answer solves, although my ctx.drawImage(gl.canvas, 0, 0) creates an array full of zeroes. gl.readPixels works just fine but is quite costly in terms of performance. preserveDrawingBuffer is set to true. Any ideas what I am missing? – Arnaud H Mar 29 '19 at 22:48
  • post your [mcve](https://meta.stackoverflow.com/a/349790/128511) in [a snippet](https://stackoverflow.blog/2014/09/16/introducing-runnable-javascript-css-and-html-code-snippets/) in a new question; – gman Mar 29 '19 at 23:53
  • If your alpha in WebGL is zero then you’ll have the issue that the canvas uses premultiplied alpha. It will multiply your colors by the alpha. The alpha being 0 that means it will zero out your colors. This is the same with just plain 2D canvas. Call getImageData, set all the alpha to zero, putImageData, then getImageData again, everything will be zero now. – gman Jun 30 '19 at 07:22