Refresh canvas element with DOM canvas

let's say that I have

var myCanvas = document.createElement('canvas'); 

and i do

 myCanvas.setAttribute("id", "my-canvas"); document.body.appendChild(myCanvas); 

Afterword I am making changes to myCanvas and want to replace html-canvas with an updated DOM canvas. The following works:

 document.getElementById("my-canvas").innerHTML = myCanvas; 

but html (via inspector) looks like

 <canvas id="my-canvas">[object HTMLCanvasElement]</canvas> 

When it should look like

 <canvas id="my-canvas"></canvas> 

How to update an element and not use innerHTML ?

+4
source share
1 answer

You do not need to update myCanvas if it is still the same node. When you create a node and add it to the DOM, then the DOM node is live. This means that all changes to myCanvas will be immediately displayed on the page.

replaceChild ()

If you want to replace the node with other nodes, you can use .replaceChild() in the parent element of the node you want to replace.

Example:

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

Where parent is the parent element element .

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

innerHTML

In your question, you are using innerHTML . If you want to simply replace the contents of one element with the contents of another element, use innerHTML for both of them.

Example:

 document.getElementById("element").innerHTML = newElement.innerHTML; 
+7
source

Source: https://habr.com/ru/post/1384634/


All Articles