Hello, my name is Ilya Chernevsky, and I work as a web developer at Evolution Company and create front end of games. Today, I want to tell you about my experience of using canvas element in games and web applications, first of all, to increase performance.
Let's look at this element in one of Evolution games, it contains approximately 4,000 DOM elements, basically, these are SVG elements with their own styles, attributes, classes, sizes, positioning, et cetera. You may say that 4,000 is not so much, perhaps, but you know what could be better? I think better is to have only one DOM element.
Firstly, what is canvas? And it's core canvas is a rectangular area where we can dynamically create graphics using JavaScript. Drawing on canvas provides a low level way to display graphics in the browser. DOM operations in the browser are considered quite slow, this is why, for example, React team developed virtual DOM concept to minimize handling DOM elements.
Let's look at the advantages and disadvantages of canvas. Let's start with the advantages. First of all, and I think, most importantly, it's performance and speed. We have just only one DOM element. Second is memory saving, since there is no need to store information about a large number of DOM elements. And control, developer can control every pixel in the drawing area. Now let's look at the existing disadvantages of this approach. One of the most obvious is animations. They are more difficult to implement. Of course we can't use animation and transition property from CSS. In the case of DOM elements, for example, when they are moved, the browser itself erases the old object and draws the new one in a new place. And in the case of Canvas, developer forced to independently draw each frame using request animation frame function from browser web API. And second con is complexity. In general, DOM elements are easier to manipulate than pixels and using Canvas API is more difficult. In the case of DOM elements, browser does part of the work for us. And finally, features of working with displays, with device pixelation, more than one. For example, when we work with smartphones, you have to keep an eye on the dimensions of the Canvas. And sometimes this can lead to unexpected artifacts. And in general, you're forced to think more about other features of Canvas that may not be immediately obvious.
When people talk about Canvas, they most often mean the Canvas API and the Canvas rendering context-2d interface. This is the simplest and low-level way to render in the browser. However, if you want to use all power of GPU, then you should consider using WebGL. WebGL API is used with the same HTML canvas element, but for rendering it's used a different drawing context, WebGL rendering context, and also use a different API, WebGL API.
Comments