javascript - update canvas element with a DOM canvas - Stack Overflow

let's say I havevar myCanvas = document.createElement('canvas');and I domyCanvas.setAttr

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?

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?

Share Improve this question asked Dec 5, 2011 at 2:31 JacksonkrJacksonkr 32.3k42 gold badges189 silver badges289 bronze badges 1
  • At best, that approach would give you a canvas inside another canvas. – Kevin Ennis Commented Dec 5, 2011 at 2:37
Add a ment  | 

1 Answer 1

Reset to default 7

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;

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744130841a4559834.html

相关推荐

  • javascript - update canvas element with a DOM canvas - Stack Overflow

    let's say I havevar myCanvas = document.createElement('canvas');and I domyCanvas.setAttr

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信