DOM vs Canvas
Author: Vincent Berger
Created: Jan 21, 2019
- Original Source code: DOM vs Canvas
In general I will cover the rendering, API's, preformance and memory compared to each other.
the DOM (Document Object Modal) is a crossplatform that inducts HTML, XHTML and XML documents as a tree structure.
To render HTML or simular tree structured crossplatforms, this is done by the browsers internal modal, simular to the DOM modal.
HTML tree hierarchy:
Document tree | |-html | |---head | |--title | |---title value | |---body | |--header tags | | |-- header values | | | | | |--etc.. etc.. | | | |
H=window.innerHeight; W=window.innerWidth; document.body.style.margin="0"; document.body.style.backgroundColor="#000"; document.body.style.overflowX="hidden"; document.body.style.overflowY="hidden"; canvas=document.createElement("canvas"); canvas.width=W; canvas.height=H; canvas.style.backgroundColor="#000"; document.body.appendChild(canvas); var draw=canvas.getContext('2d'); draw.your.context();
When a website webpage is loaded, the browser should make a current DOM of the page. Therefore the loaded DOM is object orientated and dynamic. ☯
JS, as we know, can manipulate the HTML to make changes, removes and adds elements and attributes, by this meanings it covers also the CSS and DOM events. That is alot manipulation provided by JS ☕
Lately I was wondering which one is better to create visuals, DOM manipulation or the HTML5 canvas API.
So i was creating some visual animations to compare the earlier mentioned comparisons and do some little debuggin'.
See below the visuals I used(in the end of this article you will find the source codes).
As you see the above structure, it is clear that the DOM is faster in creating the visuals in the HTML tree while the canvas is slower in rendering but does not render anything to the DOM!(see below)
As it comes to the preformance, the frames per second of the DOM is more then half of that of the Canvas.
See below what the differences are.
Not to mention what it does to the memory! I debugged it out and ran out of time to take some screenshots...(Excuse me, difference was 2.4..MB)
What is your choice of drawing to the HTML tree?