3

I am trying to get a better performance on my JavaScript-function. I draw with myPopulation=50.000 dots on a canvas and it takes apros 230ms. As I have this in another loop with a frequence of 100ms, I get a delay due to the below function.

function drawThis(intervals) {
    ctx.clearRect(0, 0, myWidth, myHeight);

    ctx.beginPath();
    for (var i = 0; i < myPopulation; i++) {
        ctx.arc(persons[i].posX, persons[i].posY, 2, 0, 2 * Math.PI);
        if (persons[i].infected) {
            ctx.fillStyle = "#FF0000";
        }
        else {
            ctx.fillStyle = "#000000";
        }
        if (i < myPopulation - 1) {
            ctx.moveTo(persons[i + 1].posX, persons[i + 1].posY);
        }
    }
    ctx.fill();

My idea was to divide myPopulation in equal intervals with a helper function like

var myIntervals = divideRangeInNParts(0, myPopulation, intervals);

and to them parallel. So the pseudo-code would be:

divide myPopulation in equal parts

drawThis(interval[0][0], interval[0][1]);
drawThis(interval[1][0], interval[1][1]);
drawThis(interval[2][0], interval[2][1]);
drawThis(interval[3][0], interval[3][1]);
[...]

wait for all of them to finish
continue

I have read a lot about JavaScript as a single-threaded language, Promises, Web Workders etc., but I could not find any solution which suits my problem.

Any idea or hint? I am new here and if there is any problem with my question, please tell me also. Thanks in advance

AndreasInfo
  • 1,062
  • 11
  • 26
  • 3
    Just as a clarification, Promises run in the same thread. Workers on the other hand, run in a separate thread. You can also look around "OffscreenCanvas" which is a way to render a canvas in a separate thread so that the drawing does not freeze your main process. – Seblor Mar 20 '20 at 12:11
  • Welcome to Stack Overflow. Yours is a good question. – O. Jones Mar 20 '20 at 12:18
  • Drawing circles is slow. I suggest you approach your problem by speeding up your drawing operations, rather than trying to use threads. See this https://stackoverflow.com/questions/4899799/whats-the-best-way-to-set-a-single-pixel-in-an-html5-canvas and this: https://stackoverflow.com/questions/7812514/drawing-a-dot-on-html5-canvas – O. Jones Mar 20 '20 at 12:25
  • Does this answer your question? [What's the best way to set a single pixel in an HTML5 canvas?](https://stackoverflow.com/questions/4899799/whats-the-best-way-to-set-a-single-pixel-in-an-html5-canvas) – O. Jones Mar 20 '20 at 12:25
  • Thank you very much for the response. (1) Changing the dots to rectangles instead of circles already improved my performance. (2) As I want more, I will follow OffscreenCanvas as a next step and I will dive in in web workers and promises. If my understanding is right, some web workers wrapped in a promise will suit my problem as I can wailt with Promise.then... for all of them to finish. I will post my outcome as soon as possible. – AndreasInfo Mar 21 '20 at 08:41

0 Answers0