Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a webgl canvas to CanvasRenderingContext2D.drawImage()

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!

like image 438
Dave Brown Avatar asked Oct 23 '14 17:10

Dave Brown


People also ask

What is difference between WebGL and canvas?

WebGL enables web content to use an API based on OpenGL ES 2.0 to perform 2D and 3D rendering in an HTML canvas in browsers that support it without the use of plug-ins. WebGL programs consist of control code written in JavaScript and shader code (GLSL) that is executed on a computer's Graphics Processing Unit (GPU).

Is WebGL faster than HTML?

In most dimensions – for instance, the number of unique draws, WebGL is four to ten times faster than HTML5. Other dimensions, like alpha rendering and texture swaps, are fast enough to be considered free.

Is WebGL faster than canvas for 2D?

However, once the WebGL graph is loaded the drawing command executes extremely fast (~0.01ms) in comparison to the 2D Canvas graph (up to 1.2ms) and so the WebGL graph is quicker to re-render when making zoom/pan interactions.


1 Answers

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>
like image 147
gman Avatar answered Oct 03 '22 05:10

gman