Retina Monitor’s Web Image Solution

什麼是Retina螢幕


今天來談談網頁圖片在視網膜(Retina)螢幕的顯示議題,首先必須來談談什麼是視網膜螢幕,其實他就是一種能在單位尺寸內顯示更多像素點的螢幕,且已經達到視網膜能辨識的極限,視網膜螢幕是由蘋果公司提出,賈伯斯在2010年iPhone 4的發表會中提到:「當你所拿的東西距離你10-12英寸(約25-30厘米)時,它的解析度只要達到300ppi這個『神奇數字』(每英寸300個像素點)以上,你的視網膜就無法分辨出像素點了。」

所以簡言之,視網膜螢幕比較一般非視網膜螢幕的不同處在於,能在同樣的範圍顯示更多的像素點,也就是PPI(Pixels Per Inch)比較高的螢幕,可參考下圖所示:

可以看到圖左在單位尺寸內顯示的像素點較少,圖右則能以更多的像素去呈現,在肉眼上就會覺得圖右會比較細緻。

接下來談談網頁圖片與視網膜螢幕之間的關係,先來看看同樣一張圖片在不同螢幕上顯示的效果。

非Retina顯示

Retina顯示

當然在美觀的立場下,我們不會希望發生這樣的視覺差異,那網頁上要如何設置才可以做到讓圖形在視網膜螢幕下也能正常的顯示呢?以下提出一些解決方案:

方案1. 透過CSS針對不同的DPR (Device Pixel Ratio)設計顯示圖片


大家如果想知道自己螢幕的DPR,可以在Chrome的主控台輸入“window.devicePixelRatio”,就可以得知目前Chrome所在螢幕的DPR值。

非Retina螢幕
Retina螢幕

可以觀察出來在兩個螢幕的DRP值是不同的,而透過CSS的樣式,可以針對這兩個不同的DPR設定顯示方式,可以參考下面的做法:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .logo{
            width: 190px;
            height: 190px;
            background-image: url("atd-icon.jpg");
            background-size: contain;
        }
        @media (-webkit-min-device-pixel-ratio: 2){
            .logo{
                background-image: url("atd-icon@2x.jpg");
            }
        }
    </style>
</head>
<body>
    <div class="logo"></div>
</body>
</html>
<script>
</script>

這邊必須針對圖檔尺寸做個說明,其中atd-icon.jpg為190 x 190,而atd-icon@2x.jpg為380 x 380。

@media (-webkit-min-device-pixel-ratio: 2)的部分是在DPR兩倍下的Media Query。

透過這樣的方式去設定,當DPR為2的時候,螢幕上的圖片改變為atd-icon_2.jpg,剛好能夠滿足在兩倍像素狀況下的顯示需求,當然以此類推,也能去設定三倍或更高倍數下的顯示圖片。

方案二. 透過img標籤的srcset屬性


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <img src="atdIcon.jpg" srcset="atd-icon@2x.jpg x2">
</body>
</html>
<script>
</script>

其中srcset=”atd-icon@2x.jpg 2x”表示在DPR等於2的時候要去呈現的圖片。

非Retina螢幕
Retina螢幕

以上兩個方法都可以解決圖片在Retina螢幕上面顯示的問題,但也要稍微注意一下支援程度:

CSS -webkit-min-device-pixel-ratio 支援列表
HTML srcset 支援列表

可以看到在IE都是無法支援的狀態,但從Edge後就開始支援,當然也可以想想目前擁有Retina螢幕的使用者,用的瀏覽器都會是哪些?說不定你不會太在乎上面那兩張圖紅色的部分。

但若是一定要有IE瀏覽器的支援,大家應該也能從上述的文章了解,我們可以透過window.devicePixelRatio的數值自行寫script進行判斷,然後再給出適合DPR的圖片,不過這邊另外推薦一個JS Library可以協助你進行這方面的判斷。

方案三. 透過Retina.js輔助進行判斷


首先到Retina.js的網站下載他們所提供的js檔,接下來至網頁引入該JS,其實網站上也有詳細的使用方法,另外檔案大小僅有約4KB並不算很大,可以參考下面的Sample Code。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="retina.min.js"></script>
</head>
<body>
    <img src="atd-icon.jpg" />
</body>
</html>

可以看到在img標籤中僅使用了原始大小的atd-icon.jpg,但因為有引入retina.min.js,他會在螢幕DPR兩倍時,自動去搜尋符合倍率下的圖片,但要記得如果不加其他屬性去設定兩倍圖片的檔名,檔名就必須按照內建的規則,也就是atd-icon@2x.jpg,當然3x也依然支援,可以到官網看一下他的使用方式,但若是使用CSS設定的背景,依然沒辦法透過retina.js達到支援IE的效果。

以上三個方法提供目前在設計網頁時,對於Retina螢幕支援的做法,若在不考慮IE瀏覽器的情況下,其實方法1+方法2就已經可以解決所有情況,但若要支援IE則可以參考方法三的做法,也歡迎大家有問題可以留言進行討論。

方案四. 使用SVG圖檔


過往我們在網頁中使用的圖片僅有GIF、PNG、JPG這三種點陣圖格式,所以在高解析度(Retina)的螢幕中,我們需要輸入不同Size的圖片,來補足像素點不足的問題,現在有了另外一種解法“SVG”圖檔。

大家可以把SVG視為一種可以放在網頁上的向量圖檔,也就是說我們以前透過Illustrator或其他向量繪圖軟體(也包含Photoshop中向量工具)繪製出來的向量圖,本身放大就不會失真,但因為要放在網頁上,我們把它轉換成了前述的三種點陣格式,才導致圖檔放大後的失真,而SVG就是保留圖片原來的向量屬性,簡言之,就是把向量圖檔放在網頁上的意思。

非Retina螢幕
Retina螢幕

感覺這個解決方案應該會比前幾項方便,但也有他必須要注意的地方:

  1. 在SVG檔案中匯入的點陣圖,在儲存成SVG時並不會被向量化,例如上圖中間的ASUS Design Logo就是匯入的點陣圖(放大後還是會模糊)。
  2. SVG字型可能會遺失,所以需要使用網路字型或是將文字轉成外框或形狀之後再轉存成SVG。
字型遺失
轉換成外框或形狀

You may also like...

37,725 Responses

  1. Colemanjab表示:

    xNudes is a tool that allows you to digitally change images, creating an illusion. https://xnudes.app/

  2. v9win表示:

    Your thing regarding creating will be practically nothing in short supply of awesome. This informative article is incredibly useful and contains offered myself a better solution to be able to my own issues. Which can be the specific purpose MY PARTNER AND I has been doing a search online. I am advocating this informative article with a good friend. I know they are going to get the write-up since beneficial as i would. Yet again many thanks.

  3. Lozxstus表示:

    купить аккаунт с прокачкой продажа аккаунтов соцсетей

  4. Dozawtus表示:

    маркетплейс аккаунтов соцсетей площадка для продажи аккаунтов

  5. The sketch is tasteful, your authored material stylish.

  6. Dannytal表示:

    mexican rx online: mexico pharmacies prescription drugs – mexican rx online

  7. Davidvew表示:

    While the Cumberland sample may contain longer chains of fatty acids, SAM is not designed to detect them. But SAM’s ability to spot these larger molecules suggests it could detect similar chemical signatures of past life on Mars if they’re present, Williams said.
    convex finance
    “Curiosity is not a life detection mission,” Freissinet said. “Curiosity is a habitability detection mission to know if all the conditions were right … for life to evolve. Having these results, it’s really at the edge of the capabilities of Curiosity, and it’s even maybe better than what we had expected from this mission.”

    Before sending missions to Mars, scientists didn’t think organic molecules would be found on the red planet because of the intensity of radiation Mars has long endured, Glavin said.
    Curiosity won’t return to Yellowknife Bay during its mission, but there are still pristine pieces of the Cumberland sample aboard. Next, the team wants to design a new experiment to see what it can detect. If the team can identify similar long-chain molecules, it would mark another step forward that might help researchers determine their origins, Freissinet said.

    “That’s the most precious sample we have on board … waiting for us to run the perfect experiment on it,” she said. “It holds secrets, and we need to decipher the secrets.”

    Briony Horgan, coinvestigator on the Perseverance rover mission and professor of planetary science at Purdue University in West Lafayette, Indiana, called the detection “a big win for the whole team.” Horgan was not involved the study.
    “This detection really confirms our hopes that sediments laid down in ancient watery environments on Mars could preserve a treasure trove of organic molecules that can tell us about everything from prebiotic processes and pathways for the origin of life, to potential biosignatures from ancient organisms,” Horgan said.

    Dr. Ben K.D. Pearce, assistant professor in Purdue’s department of Earth, atmospheric, and planetary sciences and leader of the Laboratory for Origins and Astrobiology Research, called the findings “arguably the most exciting organic detection to date on Mars.” Pearce did not participate in the research.

  8. Michaelrom表示:

    RxExpressMexico: mexican rx online – Rx Express Mexico

  9. Chesterwib表示:

    Curiosity has maintained pristine pieces of the Cumberland sample in a “doggy bag” so that the team could have the rover revisit it later, even miles away from the site where it was collected. The team developed and tested innovative methods in its lab on Earth before sending messages to the rover to try experiments on the sample.
    changelly exchange
    In a quest to see whether amino acids, the building blocks of proteins, existed in the sample, the team instructed the rover to heat up the sample twice within SAM’s oven. When it measured the mass of the molecules released during heating, there weren’t any amino acids, but they found something entirely unexpected.

    An intriguing detection
    The team was surprised to detect small amounts of decane, undecane and dodecane, so it had to conduct a reverse experiment on Earth to determine whether these organic compounds were the remnants of the fatty acids undecanoic acid, dodecanoic acid and tridecanoic acid, respectively.

    The scientists mixed undecanoic acid into a clay similar to what exists on Mars and heated it up in a way that mimicked conditions within SAM’s oven. The undecanoic acid released decane, just like what Curiosity detected.

    Each fatty acid remnant detected by Curiosity was made with a long chain of 11 to 13 carbon atoms. Previous molecules detected on Mars were smaller, meaning their atomic weight was less than the molecules found in the new study, and simpler.
    “It’s notable that non-biological processes typically make shorter fatty acids, with less than 12 carbons,” said study coauthor Dr. Amy Williams, associate professor of geology at the University of Florida and assistant director of the Astraeus Space Institute, in an email. “Larger and more complex molecules are likely what are required for an origin of life, if it ever occurred on Mars.”

  10. WalterIcort表示:

    https://rxexpressmexico.shop/# RxExpressMexico

  11. Тканевые шторы для загородного дома
    шторы в загородном доме шторы в загородном доме .+7 (499) 460-69-87

  12. Lesliecat表示:

    ?Hola fanáticos de los juegos de azar
    Ganar 20 euros por registrarte nunca fue tan sencillo. RegГ­strate, obtГ©n tu bono y disfruta de las mejores tragaperras online sin gastar un solo euro. El casino 20 euros gratis sin depГіsito es tu pasaporte hacia una experiencia de juego inolvidable.
    Recibe 20 euros gratis en casinos confiables de EspaГ±a y juega sin compromiso. – pastón bono 20 euros
    ?Que tengas excelentes logros !

  13. StevenDuase表示:

    RxExpressMexico: RxExpressMexico – Rx Express Mexico

  14. Dannytal表示:

    best online pharmacies in mexico: mexico pharmacy order online – Rx Express Mexico

  15. StevenDuase表示:

    medicine courier from India to USA: indian pharmacy online shopping – indian pharmacy online shopping

  16. Michaelrom表示:

    best india pharmacy: indian pharmacy – Medicine From India

  17. MichaelLoapy表示:

    canadian pharmacy store Buy medicine from Canada canadian drugs online

  18. WalterIcort表示:

    https://expressrxcanada.com/# canadian discount pharmacy

  19. Dannytal表示:

    Rx Express Mexico: mexican rx online – Rx Express Mexico

  20. JasonDaT表示:

    Arctic auroras
    ethena
    For getting around during winter, the Inuit here nowadays prefer snowmobiles, although they still keep their sled dogs. During winter they’ll offer intrepid visitors, wrapped up warm against the deep-freeze temperatures, dog-sledding jaunts. These can last either an hour or be part of expeditions over several days, sometimes with the added experience of learning how to build an igloo. Sisimiut on the west coast and Tasilaq in the southeast are active winter centers for dog sledding.

    Winter’s most stellar attraction, though, is northern lights watching. With little urban light pollution, Greenland is a dark canvas for spectacular displays, and aurora borealis-watching vacations are becoming more popular.

    Staying outdoors, Greenland is developing a reputation among adventure enthusiasts: from long-distance skiing expeditions and heliskiing on the icecap to hiking the 100-mile-long Arctic Circle Trail from Kangerslussuaq, where firearms need to be carried for warning shots in case of polar bear encounters.

    Life is definitely changing here. The climate crisis is eating away at its icecap and Greenland may well end up as a pawn in a game of geopolitical chess. But for now, the bright glare of international attention should shine a favorable light on one of the wildest travel destinations on Earth.

    Travel writer Mark Stratton is an Arctic specialist who has traveled to Greenland six times and counting. He’s marveled at the aurora borealis, sailed to Disko Island, dog-sledded with the Inuit, and once got stuck in an icefloe.

  21. LloydInilm表示:

    Tesla is bringing its electric cars to oil-rich Saudi Arabia amid falling global sales
    aperture finance
    Tesla will start selling its electric vehicles in Saudi Arabia, entering the Gulf region’s largest economy as the company’s global sales are sliding and CEO Elon Musk courts controversy with his role in the US government.

    The carmaker announced Wednesday that it would host a launch event in the kingdom on April 10, where it will showcase its EVs. Attendees will also have the chance to “experience the future of autonomous driving with Cybercab and meet Optimus, our humanoid robot, as we showcase what’s next in AI and robotics,” Tesla (TSLA) said.

    Tesla may struggle to gain market share in oil-rich Saudi Arabia as EVs make up a little over 1% of all car sales in the country, according to a report by consultancy PwC published in September.
    Tesla’s entry into the new market comes as the company fights battles on several fronts.

    Last year, it recorded the first annual decline in sales in its history as a public company, posting a drop of 1%.

    The company is facing intensifying competition in China, the world’s largest auto market. On Tuesday, BYD, a Chinese maker of electric and hybrid cars, reported $107 billion in annual sales for 2024, beating the near-$98 billion notched by Tesla.

    And last week, BYD unveiled an ultra-fast charging system, which it said was capable of adding 250 miles (402 km) of range in just five minutes, easily outdoing Tesla’s charging technology. Tesla’s Superchargers take 15 minutes to charge an EV, providing a range of 200 miles.

    Tesla has also suffered slumping sales in Europe. In February, the carmaker sold around 40% fewer vehicles on the continent compared with the same month in 2024, according to the European Automobile Manufacturers’ Association.

  22. MichaelLoapy表示:

    Rx Express Mexico mexico pharmacies prescription drugs Rx Express Mexico

  23. Timastus表示:

    аккаунты с балансом магазин аккаунтов

  24. AnnaTax表示:

    Some men report better post-op motivation when intimate progress starts with sildenafil dapoxetine online. Don’t just trust words – compare quality and prices yourself.

  25. F168 không ngừng nỗ lực hoàn thiện hệ thống giúp khách hàng có giây phút giải trí tuyệt vời. Hãy tham gia cùng chúng tôi bức phá giới hạn! Website: https://elvallenato.com.co/

  26. Michaelrom表示:

    Rx Express Mexico: mexican rx online – mexico drug stores pharmacies

  27. Dannytal表示:

    mexico pharmacy order online: Rx Express Mexico – mexico pharmacy order online

  28. Лучшие мастерские по пошиву штор, профессиональный пошив штор..
    Пошив штор для вашего дома, по доступным ценам..
    Пошив штор на заказ, по вашим размерам..
    Изготовление штор на заказ, закажите онлайн..
    Пошив штор с доставкой, по вашим требованиям..
    Лучшие ткани для пошива штор, по выгодным ценам..
    Дизайнерские шторы на любой интерьер, Обратитесь сегодня..
    Шторы на любой вкус и цвет, от ведущих мастеров..
    Эксклюзивные шторы на заказ, по индивидуальному проекту..
    Выберите качественный пошив штор, оформляйте заказ онлайн..
    Идеальные шторы для вашего пространства, по лучшим ценам..
    Премиум пошив штор для интерьера, по индивидуальному дизайну..
    Пошив штор с профессиональным монтажом, от профессионалов..
    Индивидуальный дизайн штор, с индивидуальным подходом..
    Эксклюзивный дизайн штор, с современными технологиями..
    Высокое качество и стиль, по вашему стилю..
    Индивидуальные шторы на заказ, по оптимальной цене..
    пошив штор пошив штор . “Ткацкий”

  29. Michaelrom表示:

    mexican drugstore online: mexican online pharmacy – mexican online pharmacies prescription drugs

  30. AnnaTax表示:

    Liam’s wife held his hand at the clinic-both left with hope and cenforce 150. Each brave decision you make today moves you closer to the life where energy, connection, and pride are fully yours again.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。