将webgl画布传递给CanvasRenderingContext2D.drawImage() [英] passing a webgl canvas to CanvasRenderingContext2D.drawImage()

查看:118
本文介绍了将webgl画布传递给CanvasRenderingContext2D.drawImage()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个画布的内容复制到另一个画布。

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

源画布有一个webgl上下文。

The source canvas has a webgl context.

目标画布有一个2d上下文。

The destination canvas has a 2d context.

我的代码如下:

destinationContext.drawImage(sourceCanvas, 0, 0);

这适用于Firefox和IE,但它在Chrome中不起作用。为什么不呢?

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

谢谢!

推荐答案

这是一些有效的代码。

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>

这是一些有延迟的工作代码。如果你没有在你绘制的同一事件中复制WebGL画布,那么你需要其中一个解决方案。即使这个问题是关于 toDataURL ,所有相同的事情都适用于使用带有 drawImage 的WebGL画布。

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>

这篇关于将webgl画布传递给CanvasRenderingContext2D.drawImage()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆