7

I'm working with a customHTML section, currently I'm using a canvas html5 element. Now, I need to display an image, but not sure if it will be a good idea to draw it in this canvas element or use a <img> html element directly.

My first approach is this:

a)

 var customHTML = "<canvas id='viewport'></canvas>"
 var canvas = document.getElementById('viewport'),
 context = canvas.getContext('2d');

 make_base();

 function make_base()
 {
   base_image = new Image();
   base_image.src = 'img/base.png';
   base_image.onload = function(){
   context.drawImage(base_image, 100, 100);
 }

Second approach:

b)

 var customHTML = "<img src='../images/myicons/pin.png'>"

I would like to know if there is any advantage in using this canvas and drawing logic, instead of using directly an <img> html element. Performance? Resources?

Please, let me know if a) or b) is the best approach.

I want to use this customHTML element as a pushpin in Bing Maps.

Any help will be appreciated.

Alberto Montellano
  • 5,886
  • 7
  • 37
  • 53

2 Answers2

5

The img element works since the dawn of time. Png image support also since a very long time. The other piece of code always needs Javascript, and needs a more modern browser that supports HTML 5 canvas. Some of these advantages may not apply when the usecase is a pushpin in Bing Maps, since Bing Maps will have requirements on its ownn.

In general performance there won't be much difference, and this may even vary between browsers and versions. Drawing an image is pretty easy anyway (compared to, say, animation), so I wouldn't worry about it.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
  • 1
    +1 Yep, using img+CSS is sweet and simple for this requirement. – markE Mar 31 '14 at 20:15
  • 1
    One advantage in canvas is, use an external image as the backdrop for a line graph, eg:- https://jsfiddle.net/api/mdn/ – Kuhan Aug 23 '17 at 17:00
1
base_image.onload = function() {
  context.drawImage(base_image, 100, 100);
}

assigns the function as an event handler that gets called only when the image in question has finished downloading.

base_image.src = 'img/base.png';

begins the download of the image and it may be regarded as an asynchronous (bon-blocking) call for the image.

<img src='../images/myicons/pin.png'> begins drawing as the page loads and you get this line-by-line display of the image as it's data trickles in.

The difference between these approaches is at least partially a UI consideration and especially evident with large images and slow internet connection. Not so much an issue with fast connections, small/cached images.

michaelI
  • 11
  • 3
  • So your saying that if you wanted to do something with the photo after it finishes loading then the first approach would be better? Like if I wanted to get the height and width of it, so make adjustments to it, then that would require the photo to be loaded before doing these things? – kiwicomb123 Nov 14 '17 at 04:51