0

So in this project that I am writing i have a wheel that contains of images. They are drawn with the canvas.getContext('2d').drawImage() function. My first idea was that I would just get the img in the loop as the following.

while(wheel){

    //all other code ^^        

    var imageObj = new Image();
    imageObj.src = getImgFromKeyword(passedLocations[i].keyword); //Will return a URL to an image
    var x = Math.cos(dp/2 + dp * i ) * (pr -  startPosInSlice) - imgsize/2;
    var y = Math.sin(dp/2 + dp * i ) * (pr - startPosInSlice) - imgsize/2;
    ctx.drawImage(imageObj, x, y, imgsize, imgsize);
}

However since i am running this in a loop I am actually loading that URL litteraly THOUSANDS of Thousands of time. I reckon that this will be rather insufficient to the runtime. Would storing the images in an array upon initialize and then refer to that object in the drawing be more efficient.

Best regards

Albin wärme
  • 251
  • 1
  • 14

1 Answers1

0

You shouldn't redeclare imageObj every time, so you need to put this outside your loop. It's also useless to reset the src property every time, so this would be the best way:

let imageObj = new Image();
imageObj.src = // load url
while (wheel) {
  // draw your stuff
}
kwyntes
  • 1,045
  • 10
  • 27