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.

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top