切换画布上下文 [英] Switch canvas context
问题描述
有没有办法在上下文中使用 2d一个?
这样的事情的目标是在渲染过程中出现错误时显示一个调试BSOD。
如果不可能,那么:
- 我可以在画布上嵌入一个html元素,并强制这个元素有就像画布一样(即使最后一次调整大小)?
- 可以替换一个dom节点,还可以更新有关旧节点的每个引用以反映更改?
这是我目前的最小电话代码。 Canvas是一个包含由WebGL API填充的画布的DOM节点,回调是一个处理单个框架的函数。
函数失败(cvs,e){
var ctx = cvs.getContext('2d'); // Fail here,如果cvs.getContext('webgl')已被调用,返回`null'
ctx.fillStyle ='rgb(0,0,0)';
ctx.fillRect(0,0,cvs.width,cvs.height);
ctx.fillStyle ='rgb(255,255,255)';
ctx.font ='bold 12px sans-serif';
ctx.fillText(e.toString(),0,0);
}
函数foobar(canvas,callback){
try {
callback();
} catch(e){
failure(canvas,e);
throw e;
} finally {
requestAnimationFrame(arguments.callee);
}
}
根据规范,简短的答案几乎没有。
每个画布都有一个主要的上下文。这是在画布上调用的第一个上下文。在画布上创建非主要上下文可能会在不同的浏览器上执行某些操作,但我永远不会依赖它。
我将会有一个第二个画布覆盖在第一个并保持相同的宽度和高度属性。我会隐藏一个,而不是隐藏另一个(或者当你想要看到它时,只是取消隐藏2D)。
或者为了简单起见,只需使用PNG,的DIV也保持画布。换句话说:
Div容器有黑色背景并保持:
-PNG(居中)
- 3D画布
然后,当您想要显示错误png时,您只需隐藏3D画布(可选)取消隐藏PNG)
Assuming that I have a WebGL canvas (by calling getContext("experimental-webgl")).
Is there any way to switch context later for using a "2d" one ?
The goal of such thing would be to display a debug BSOD-like when an error happening during rendering.
If it's not possible, then :
- Can I embed an html element over a canvas, and force this element to have exactly the same same that the canvas (even if this last is resized) ?
- Can I replace an dom node, and update every reference about the old one to reflect the changement ?
[edit] This is my current minimal call code. Canvas is a DOM node containing a canvas which is filled by WebGL API, and callback is a function which process a single frame.
function failure(cvs, e) {
var ctx = cvs.getContext('2d'); // Fail here, returns `null' if cvs.getContext('webgl') has been called
ctx.fillStyle = 'rgb(0, 0, 0)';
ctx.fillRect(0, 0, cvs.width, cvs.height);
ctx.fillStyle = 'rgb(255, 255, 255)';
ctx.font = 'bold 12px sans-serif';
ctx.fillText(e.toString(), 0, 0);
}
function foobar(canvas, callback) {
try {
callback();
} catch (e) {
failure(canvas, e);
throw e;
} finally {
requestAnimationFrame(arguments.callee);
}
}
The short answer is pretty much no, according to the spec.
Every canvas has what is called a primary context. This is the first context that is invoked on a canvas. Making a non-primary context on a canvas might do some things on different browsers but I would never, ever depend on it.
I would instead have a second canvas that is overlaid over the first and maintains the same width and height attributes. I would then hide one and unhide the other (or just unhide the 2D one when you want it seen).
OR just use a PNG for simplicity's sake., centered inside of a DIV that also holds the canvas. In other words:
Div container has black background and holds:
-PNG (centered)
-3D Canvas
Then when you want the error png to be displayed you just hide the 3D canvas (and optionally unhide the PNG)
这篇关于切换画布上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!