update canvas element with a DOM canvas

走远了吗. 提交于 2021-01-27 06:42:23

问题


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?


回答1:


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.

Example:

document.getElementById("parent").replaceChild(element, newElement);

Where parent is the parent element of element.

<div id="parent">
  <canvas id="element"></canvas>
</div>

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 use innerHTML on both of them.

Example:

document.getElementById("element").innerHTML = newElement.innerHTML;


来源:https://stackoverflow.com/questions/8380411/update-canvas-element-with-a-dom-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!