I am under a situation that i have two canvas, and i want to display the same object in both canvas (in fact i have to display different objects in each canvas, but i want t
var canvas = document.getElementById("canvas"),
canvas2 = document.getElementById("canvas2");
gl = canvas.getContext("experimental-webgl");
gl2 = canvas.getContext("experimental-webgl");
I think you missed the reference to the second canvas element
No, unfortunately you can not share WebGL objects across canvases in WebGL 1.0
What are you trying to accomplish?
Some solutions:
Split 1 canvas
If you need multiple views like many 3D modeling programs you can split a single canvas using gl.enable(gl.SCISSOR_TEST)
, gl.scissor
and gl.viewport
. Here's one example
Draw to one canvas, then copy to other canvases
In this case you render to an offscreen canvas with WebGL then use multiple visible canvas 2d canvases to display by using drawImage.
gl = offscreenCanvas.getContext("webgl");
ctx1 = onscreenCanvas1.getContext("2d");
ctx2 = onscreenCanvas2.getContext("2d");
// render whatever you want to appear in onscreenCanvas1
renderScene(scene1Settings, gl);
// copy the result to offscreenCanvas1
ctx1.drawImage(gl.canvas, ...);
// render whatever you want to appear in onscreenCanvas2
renderScene(scene2Settings, gl);
// copy the result to offsceenCanvas2
ctx2.drawImage(gl,canvas, ...);
Make 1 canvas the size of the window, put it in the background, use the first technique (scissor, viewport) and getBoundingClientRect
to render exactly where some other element is.
In this case you make a single WebGL canvas the size of the window
and using CSS put it in the background. Then you create a placeholder
<div>
or other element to represent where you want a canvas to
appear.
You can then ask the browser exactly where that element appears and use that info to set the viewport and scissor and then render to that area to make it appear like it's a canvas
Example1, Example2