Benefit to use canvas instead of img?

雨燕双飞 提交于 2020-01-03 05:54:05

问题


i am currently building a mobile app and i'm just wondering if it's better (performance wise) to use canvas or img tags. i'll be querying my website for the actual image. just wondering if there is a benefit of one over the other.


回答1:


The main benefit is to avoid unnecessary browser decode.

For browsers to paint an image onto screen, they would need to:

  1. Retrieve the encoded contents of the image file
  2. Decode the image from its original JPEG, GIF, PNG or WebP format to a bitmap in memory
  3. Paint it onto the screen

Performance issues arise when users scroll and resize. Decoding is particularly expensive. Yet when we scroll up and down the page, browser would attempt to retrieve the memory previously occupied by off-screen images (that is, the content outside of the current scroll region). This means that whenever an image reappears from the edge of the screen, the browser would have to go through the same expensive decoding process all over again. When we have a lot of images splashed over a long page, the browser would likely stutter on scroll.

What's different about canvas: browser doesn't recycle the decoded information inside of canvas. So by using canvas to render the image, we avoid unnecessary decoding.

But of course, if I'm targeting mobile devices, I'd switch back to image tags and let browsers do their job since memory is scarce.

I think this is a browser-specific tactic to deal with the conflict between decoding images and limited memory. I was talking about Chrome more specifically, since the process is visible in the Timeline dev tools.




回答2:


No! If you're displaying static content, <canvas> is slower and much more obtuse. <canvas> and <img> do completely different things, the former being for dynamic graphics using JavaScript and the latter being for static images retrieved from a URI.




回答3:


Browsers tend to be optimised for loading IMG sources while the HTML is streaming: so you'll see an image before the page has loaded completely. Canvas, on the other hand, will be dependent on the DOM being loaded, so (typically) won't load until the DOMContentLoaded event has fired. Add to that the latency in creating a Canvas context and the memory requirements and it almost certainly isn't what you want if the images are truly static.

If you want to do something fancy with the image why not load the image in an IMG tag and then convert it to a canvas once loaded to do the transformations?



来源:https://stackoverflow.com/questions/10925047/benefit-to-use-canvas-instead-of-img

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!