Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to copy another canvas's data on the canvas with getContext('webgl')?

I have a canvas for showing medical image and I have another canvas for annotating images by draw shape or line.

when I draw a line on canvas#2 I want to copy drawn line on canvas#1 something like this:

  var context = canvas1.getContext('2d');
  context.drawImage(canvas2,0,0);

but because my canvas#1 has a getContext('webgl') I can't do that.

I mean how to simulate

  drawImage() for getcontext('webgl')?

I really appreciate any help or advice.

Regards;

Zohreh

like image 383
Zohreh Avatar asked Oct 21 '22 21:10

Zohreh


2 Answers

Well, you could just use the toDataURL method of the webgl canvas to convert it into an image. Then draw it on the 2d context.

ctx2D.drawImage(webGLCanvas.toDataURL("image/png"), 0, 0);

In this case I believe you might have to set the preserveDrawingBuffer propertie of the webgl canvas to true when initializing it.

...getContext("webgl", {preserveDrawingBuffer: true});
like image 171
Delta Avatar answered Nov 01 '22 08:11

Delta


I had a similar problem with Emscripten, needed to copy WebGL canvas to another empty canvas. I used this code but got empty screen.

var sourceCanvasWebGL = document.getElementById( "canvas" );
var destinationCanvas = document.getElementById( "canvasCopy" );
var destinationCanvasContext = destinationCanvas.getContext('2d');
destinationCanvasContext.drawImage(sourceCanvasWebGL, 0, 0);

After some googling (Saving canvas to image via canvas.toDataURL results in black rectangle) I figured out that because WebGL is using 2 buffers while drawing I am copying the old buffer with empty content.

Problem was solved by setting preserveDrawingBuffer: true in the code used to make WebGL drawing.

sourceCanvasWebGL.getContext("webgl2", { preserveDrawingBuffer: true })

P.S. As an alternative you could make an image copy right after rendering the canvas. If so you do not need preserveDrawingBuffer.

like image 33
Michael Klishevich Avatar answered Nov 01 '22 08:11

Michael Klishevich