使用DOM画布更新canvas元素 [英] update canvas element with a DOM canvas
问题描述
假设我有
var myCanvas = document.createElement('canvas');
我愿意
myCanvas.setAttribute("id", "my-canvas");
document.body.appendChild(myCanvas);
后记我更改了 myCanvas
,并想用更新后的 DOM
画布替换 html画布.以下作品:
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;
但是html(通过检查器)看起来像
but the html (via inspector) looks like
<canvas id="my-canvas">[object HTMLCanvasElement]</canvas>
什么时候看起来像
<canvas id="my-canvas"></canvas>
如何更新元素而不使用 innerHTML
?
How can I update the element and not use innerHTML
?
推荐答案
如果 myCanvas
仍然是同一节点,则不必更新.创建节点并追加节点时,该节点即为DOM,而DOM节点为 live .这意味着 myCanvas
上的所有更改将立即反映在页面中.
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 the myCanvas
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.
示例:
document.getElementById("parent").replaceChild(element, newElement);
其中 parent
是 element
的父元素.
<div id="parent">
<canvas id="element"></canvas>
</div>
innerHTML
在您的问题中,您使用的是 innerHTML
.如果您只想用一个元素的内容替换另一个元素的内容,则在这两个元素上都使用 innerHTML
.
示例:
document.getElementById("element").innerHTML = newElement.innerHTML;
这篇关于使用DOM画布更新canvas元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!