HTML5 Canvas fillRect slow

I am trying to write a simple raycaster using an HTML5 canvas, and I get a terrible framework. The Firefox profiler reports that 80% of my runtime is wasted in context2d.fillRect (), which I use for each column for floors and ceilings, and for a pixel on textured walls. I stumbled upon this question and found that fillRect was faster than 1x1 px images at 40% on chrome and 4% on firefox. They mention how he still calculates alpha material, although I would suggest that if alpha is 1, will it have a pass for opaque rendering? Are there any other methods for making a lot of rectangles and pixel pancakes with javascript that I should try?

+4
source share
2 answers

There are two solutions you could try to reduce the CPU usage of your renderings.

Try using requestAnimationFrame so that your browser displays your canvas graphics whenever it is ready, and especially only when the user has a canvas tab open in the browser. Additional information: https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame

The second solution, depending on whether part or all of your content is dynamic, is to pre-render parts of your canvas on another β€œhidden” canvas in memory using JavaScript (for example, you split your main canvas into 4 sub-canvas, then you only need to draw 4 elements on the screen).

PS: If you use a Mac using Firefox in conjunction with multiple canvas rendering, this will increase the use of your processor compared to Chrome

Hope this helps

+1
source

The solution I found is to put a call to fillRect () inside the path every time you call it:

canvasContext.beginPath(); canvasContext.rect(1, 1, 10, 10); canvasContext.fill(); canvasContext.closePath(); 

It seems that calling rect () adds the path to the previous call to rect (), if used incorrectly, this could lead to a memory leak or increased resource usage.

0
source

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


All Articles