从不在 DOM 树中的 jquery 对象复制画布节点

发布于 2024-11-08 07:30:18 字数 165 浏览 9 评论 0原文

最近一段时间我一直在开发游戏引擎,最近我添加了我所说的影子 DOM。它只是一个包含 div 的 jQuery 对象,因此我可以向其中添加内容。每经过一帧,shadow DOM 的内容就会复制到多个视口。我的问题是我无法复制画布元素的状态。

有没有办法解决这个问题,而不必更新每个视口中的每个画布元素?

I have been working on a game engine for the last little while and I recently added what i call a shadow DOM. All it is a jQuery object that contains a div so i can append things to it. Every time a frame is elapsed the contents of the shadow DOM is copied to multiple viewports. My problem is that I can't copy the state of the canvas elements.

Is there anyway to get around this without having to update each canvas element in each viewport?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

扶醉桌前 2024-11-15 07:30:18

我发现最好的方法是创建另一个画布,然后通过以下方式将旧画布中的数据直接添加到新画布中:

//Create a blank canvas to apply the old canvas to
var newCanvas = jQuery('<canvas></canvas>'),
    newCanvasContext = newCanvas.getContext('2d');

//size the new canvas to mirror the old canvas
newCanvas[0].width = oldCanvas[0].width;
newCanvas[0].height = oldCanvas[0].height;

//copy the old canvas onto the new canvas with drawImage();
newCanvasContext.drawImage(oldCanvas[0], 0, 0, oldCanvas[0].width, oldCanvas[0].height);

我发现仅复制画布节点是不够的复制画布及其数据需要上述内容。

I found the best way to do this is by creating another canvas then adding the data from the old canvas directly to the new one in the following way:

//Create a blank canvas to apply the old canvas to
var newCanvas = jQuery('<canvas></canvas>'),
    newCanvasContext = newCanvas.getContext('2d');

//size the new canvas to mirror the old canvas
newCanvas[0].width = oldCanvas[0].width;
newCanvas[0].height = oldCanvas[0].height;

//copy the old canvas onto the new canvas with drawImage();
newCanvasContext.drawImage(oldCanvas[0], 0, 0, oldCanvas[0].width, oldCanvas[0].height);

I found that just copying the canvas node is not enough. The above is needed to duplicate a canvas and its data.

囍笑 2024-11-15 07:30:18

这里对您的问题有一个很好的答案:在 JavaScript 中深度克隆对象最有效的方法是什么?

There's an excellent answer to your question right here on SO: What is the most efficient way to deep clone an object in JavaScript?

白馒头 2024-11-15 07:30:18

找到了解决方案。我必须为画布的每个副本手动复制图像数据。请参阅 有什么方法可以克隆 HTML5 canvas 元素及其内容? 了解详情。

Found a solution. I had to copy the image data manually for each copy of the canvas. See Any way to clone HTML5 canvas element with its content? for details.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文