Click here to Skip to main content
15,885,953 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Receives an object containing image information as json and draws it on the canvas.
The following is the inside of the draw function.
In this case, which is better, createElement(img) or new Image()? and Why?

What I have tried:

JavaScript
canvas = document.getElementById('canvas'+id);
ctx = canvas.getContext('2d', {alpha:false});
ctx = fillStyle='#379fef';

/*object the contained img */

/** createElement **/
page.data.image = document.createElement('img');
page.data.image.src = page.data.src;

let img = page.data.image;
if(img.complete){
   ctx.drawImage(img,0,0);
}else{
   img.onload = function(){
       context.drawImage(img,0,0);
   }
}

/******** new image() *********/
let img = new Image();
img.src = page.data.src;
img.onload = function(){
    ctx.drawImage(img, 0, 0);
}
Posted
Updated 15-May-22 22:33pm

1 solution

The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document.createElement('img').
The only difference between new Image() and document.createElement('img') is that one line is shorter than the other.

However, your two code blocks have other differences as well. Your first block stores the image in the page.data object, whereas the second block stores it in a local variable.

And neither block is entirely correct. You should assign the onload handler before assigning the src.
 
Share this answer
 
Comments
Chopin2001 19-May-22 0:15am    
Thanks! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900