Javascript – How does Javascript CANVAS works


Javascript CANVAS is amazing: it allows us to draw something like lines, polygons on the browser screen.

I wonder how does Javascript CANVAS works. For example to draw a line, does it use a series aligned tiny images to simulate the line or some other approach?

Thanks in advance.

Best Solution

Any reasonable implementer would just use a bitmap (stored internally in the browser), and draw to that using OS native drawing commands.

Why does it matter? It's not at all related to HTML+CSS, if that's what you're wondering.

More detail, for detail's sake:

When the browser's HTML parser sees a canvas element (of a given width & height) it needs to allocate an onscreen pixmap to cover that area. It either does this manually (i.e. malloc()) or it calls into some OS native drawing API to create a surface to draw on. The OS native API could be Windows, Gtk, Kde, Qt, or any other drawing library that the implementer of the browser chose. Also, it's highly dependent on the operating system. Internet Explorer probably calls into some Windows native library (i.e. DirectX or WinFooBarMethod()).

Once the drawing surface is created, it's made accessible to the internal guts of the JavaScript interpreter, likely via a pointer or handle to the constructed drawing surface. Then, when the JS interpreter sees an invocation of one of the canvas methods, it turns this into a call to the appropriate OS native command.

So, using the Windows 3.1 style metaphor:

"new canvas(width, height)" = "WinCreatePixmap(width, height)" 
"canvas.setPixel(x,y,color)" = "WinSetPixel(x,y,color)"

And using a manually managed pixmap:

"new canvas(width, height)" = "malloc(width * height * sizeof(Pixel))"
"canvas.setPixel(x,y,color)" = "canvas[x][y] = color;" 

Again, it shouldn't matter to the JavaScript developer how these methods are implemented. The only people who need to care are the ones who are writing HTML5 compliant web browsers with canvas support.