@K3N 的赞成答案大约有一点是正确的:你的问题不是来自</canvas>
结束标签未显示在检查器中,但来自您从已经初始化了 webgl 的画布中获取 2D 上下文的尝试。
But,
虽然在 HTML5 中确实如此一些元素 https://www.w3.org/TR/html-markup/syntax.html#void-element不需要结束标签,因为canvas https://html.spec.whatwg.org/multipage/dom.html#concept-element-tag-omission
text/html 中的标签省略:
两个标签都不可省略。
这是一个小的反证明其他小提琴 https://jsfiddle.net/epistemex/w5aaodxj/,既然是,<script>
内容应该在遇到时直接执行,并且现代浏览器在遇到结束标记之前使画布元素在 DOM 中可用,这些浏览器能够执行这个简单的脚本(IE9 不会),但这肯定是您的事情想要避免:
canvas{border: 1px solid}
<canvas>
<p>I'm not there</p>
So it's just your inspector, or maybe internally your browser which doesn't show it, but you must write it in your markup.
(Actually, if we're talking about chrome, it's only the inspector which doesn't show it, you can see it by calling the outerHTML
property of the canvas element, the closing tag will be there.)
对于解决方案,
您想要做的是将画布导出为静态图像。
为此,自toBlob https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob是一个 HTMLCanvasElement 的方法,你不需要当前上下文,你只需要最后一部分答案 https://stackoverflow.com/questions/33242959/saving-png-files-with-filesaver-js/33243864#33243864您在问题中向我们指出了一些小的调整:
正如中所解释的那样这个答案 https://stackoverflow.com/a/32641456/3702797 by gman https://stackoverflow.com/users/128511/gman,webgl canvas 是双缓冲的,并且浏览器会尽快清除绘图缓冲区,除非上下文是使用preserveDrawingBuffer: true
的论点getContext()
method.
但这种说法会对性能产生严重影响,最好的推荐方法是调用toBlob()
方法,在与渲染相同的调用中,同步进行。
由于它已经在那里得到了很好的解释,我不会在这个主题上扩展太多,但请注意,它也涉及toDataURL()
and some2dCanvas.drawImage(yourWebglCanvas,x,y)
.