簡體   English   中英

如何使用 getContext('webgl') 在畫布上復制另一個畫布的數據?

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

我有一個用於顯示醫學圖像的畫布,還有另一個用於通過繪制形狀或線條注釋圖像的畫布。

當我在畫布#2 上畫一條線時,我想在畫布#1 上復制畫線,如下所示:

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

但是因為我的畫布#1 有一個 getContext('webgl') 我不能這樣做。

我的意思是如何模擬

  drawImage() for getcontext('webgl')?

我真的很感激任何幫助或建議。

問候;

佐雷

好吧,您可以使用 webgl 畫布的toDataURL方法將其轉換為圖像。 然后在 2d 上下文中繪制它。

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

在這種情況下,我相信您可能必須在初始化時將 webgl 畫布的preserveDrawingBuffer屬性設置為 true。

...getContext("webgl", {preserveDrawingBuffer: true});

您可以使用 2D 畫布作為屏幕畫布,並在更新 WebGL 畫布時在其上繪制 WebGL 畫布,然后再繪制任何注釋。

drawWebGLStuff(webGLCtx);

// Copy image data of WebGL canvas to 2D canvas.
// This should be done right after WebGL rendering,
// unless preserveDrawingBuffer: true is passed during WebGL context creation,
// since WebGL will swap buffers by default, leaving no image in the drawing buffer,
// which is what we want to copy.
ctx2D.drawImage(webGLCanvas, 0, 0);

drawAnnotations(ctx2D);

(注釋可以從形狀列表中的每一幀渲染或繪制到另一個屏幕外畫布,然后繪制到類似於 WebGL 畫布的主(屏幕上)畫布。)

或者您可以簡單地使用絕對定位和z-index將頁面上的畫布分層

<div style="position: relative;">
   <canvas id="layer1" width="100" height="100" 
       style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
   <canvas id="layer2" width="100" height="100" 
       style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>

Emscripten 也有類似的問題,需要將 WebGL 畫布復制到另一個空畫布。 我使用了此代碼,但屏幕為空。

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

經過一些谷歌搜索( 通過 canvas.toDataURL 將畫布保存到圖像導致黑色矩形)我發現,因為 WebGL 在繪圖時使用了 2 個緩沖區,所以我正在復制帶有空內容的舊緩沖區。

通過在用於制作 WebGL 繪圖的代碼中設置preserveDrawingBuffer: true解決了問題。

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

PS 作為替代方案,您可以在渲染畫布后立即制作圖像副本。 如果是這樣,您不需要preserveDrawingBuffer。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM