使用画布而不是img的好处? [英] Benefit to use canvas instead of img?

查看:69
本文介绍了使用画布而不是img的好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建一个移动应用程序,我只是想知道使用canvas或img标签是否更好(性能明智).我将查询我的网站的实际图像.只是想知道一个人是否比另一个人有好处.

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.

推荐答案

主要优点是避免不必要的浏览器解码.

The main benefit is to avoid unnecessary browser decode.

对于要在屏幕上绘制图像的浏览器,他们需要:

  1. 检索图像文件的编码内容
  2. 将图像从其原始JPEG,GIF,PNG或WebP格式解码为内存中的位图
  3. 将其绘制到屏幕上

用户滚动和调整大小时会出现性能问题.解码特别昂贵.但是,当我们上下滚动页面时,浏览器将尝试检索以前由屏幕外图像(即当前滚动区域之外的内容).这意味着,每当图像从屏幕边缘重新出现时,浏览器将不得不重新进行同样昂贵的解码过程.当我们在长页面上溅出大量图像时,浏览器可能会在滚动时停顿.

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.

我认为这是一种特定于浏览器的策略,用于处理解码图像和有限内存之间的冲突.我说的是Chrome,因为该过程在Timeline开发工具中可见.

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.

这篇关于使用画布而不是img的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆