使用 DOM 画布更新画布元素
假设我已经
var myCanvas = document.createElement('canvas');
并且在
myCanvas.setAttribute("id", "my-canvas");
document.body.appendChild(myCanvas);
后记中对 myCanvas
进行了更改,并希望用更新的 DOM
画布替换 html-canvas。以下内容有效:
document.getElementById("my-canvas").innerHTML = myCanvas;
但是 html(通过检查器)看起来像
<canvas id="my-canvas">[object HTMLCanvasElement]</canvas>
当它应该看起来像时
<canvas id="my-canvas"></canvas>
如何更新元素而不使用 innerHTML
?
let's say I have
var myCanvas = document.createElement('canvas');
and I do
myCanvas.setAttribute("id", "my-canvas");
document.body.appendChild(myCanvas);
Afterwords I make change to myCanvas
and want to replace the html-canvas with my updated DOM
canvas. The following works:
document.getElementById("my-canvas").innerHTML = myCanvas;
but the html (via inspector) looks like
<canvas id="my-canvas">[object HTMLCanvasElement]</canvas>
When it should look like
<canvas id="my-canvas"></canvas>
How can I update the element and not use innerHTML
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果 myCanvas 仍然是同一节点,则不必更新它。当您创建一个节点并将其附加到 DOM 时,那么该 DOM 节点就是活动。这意味着
myCanvas
上的所有更改都将立即反映在页面中。"
如果您想用不同的节点替换节点,您可以使用
.replaceChild()
位于要替换的节点的父元素上。示例:
其中
parent
是element
的父元素。innerHTML
在您的问题中,您使用的是
innerHTML
。如果您只想将一个元素的内容替换为另一个元素的内容,请对这两个元素使用innerHTML
。示例:
You don't have to update
myCanvas
if it is still the same node. When you create a node and you append it do the DOM then the DOM node is live. It means that all changes on themyCanvas
will be immediately reflected in the page.replaceChild()
In case you want to replace a node with different node you can use
.replaceChild()
on the parent element of the node you want to replace.Example:
Where
parent
is the parent element ofelement
.innerHTML
In your question you are using
innerHTML
. If you want just to replace a content of one element by a content of another element, then useinnerHTML
on both of them.Example: