Home > Back-end >  Why HTML canvas does not show anything after adding new element?
Why HTML canvas does not show anything after adding new element?

Time:01-11

Why HTML canvas does not show anything after adding new element?

I have following HTML canvas, which works fine if not appending now element to Dom:

<canvas , width="1025", height="600"> </canvas>

enter image description here

but everything disappear after I added new div into window ($ is querySelector):

$(".class-main")!.innerHTML  = "<div class='class-chat' style='; color: white;'> Hi </div>";

enter image description here

As image shown, the text Hi displayed normally, but the canvas just disappeared after I added new div. If I removed this line of code, canvas shown again. I didn't change anything in my code except the line that added new element. There's also no error in console, means code run successfully but canvas does not show anything.

Why is that happened? How can I do?

CodePudding user response:

Setting an element's innerHTML rewrites it completely from scratch.

When you update an element's innerHTML like this:

$(".class-main").innerHTML = "anything"

the browser reads the element's current innerHTML as a string, concatenates it with your new string, writes the resulting string into the DOM (replacing whatever was there before), and then parses that DOM for display. Any information that wasn't in the literal HTML, such as javascript event bindings on any contained elements or (in your case) the script-generated contents of a <canvas> tag, will be lost in the process.

Instead of rewriting the entire contents of the element, use other DOM methods such as appendChild() or after() or etc to just insert the new content, leaving your existing canvas content alone.

// bind an event to the DOM:
document.querySelector('.bar').onclick = () => {
  console.log('clicked')
};


// create a new DOM element
let newElement = document.createElement('div');
newElement.innerHTML="This is new content";

// this will preserve the click event:
document.querySelector('.foo').after(newElement)

// this would destroy the click event:
// document.querySelector('.foo').innerHTML  = "This is new content"
<div >
  This is the original content.
  <button >Click me</button>
</div>

  • Related