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,810 Responses

  1. AnnaTax表示:

    Setting realistic goals for recovery makes the journey feel more manageable and motivating with viagra connect. Meet where silence speaks louder than words and hearts understand.

  2. Sazrznf表示:

    Купить диплом ВУЗа по доступной стоимости возможно, обращаясь к надежной специализированной компании. Купить документ института вы можете в нашей компании. lgmtech.co.uk/employer/originals-diplomsi

  3. AnnaTax表示:

    Research into nocturnal erections shows improvement in frequency after starting levitra wiki. Proper doses protect your health while unlocking real results.

  4. quooker表示:

    I am glad to talk with you and you give me great help

  5. Dannytal表示:

    MedicineFromIndia: indian pharmacy – indian pharmacy online

  6. Lazrhzl表示:

    Диплом ВУЗа РФ!
    Без наличия диплома сложно было продвинуться по карьерной лестнице. Именно из-за этого решение о покупке диплома следует считать рациональным. Приобрести диплом ВУЗа jobs.foodtechconnect.com/companies/gosznac-diplom-24

  7. mostbet_aqKn表示:

    мостбет уз кириш https://mostbet3026.ru/ .

  8. Lozxstus表示:

    покупка аккаунтов покупка аккаунтов

  9. Michaelrom表示:

    RxExpressMexico: mexican rx online – mexico pharmacy order online

  10. Thanks for your patience and sorry for the inconvenience!

  11. F168表示:

    F168 – Sân chơi cá cược đỉnh cao, nơi hội tụ tinh hoa giải trí hiện đại và phong cách thượng lưu. Đăng ký ngay hôm nay để khám phá ưu đãi.

  12. Michaelrom表示:

    mexican online pharmacy: mexico pharmacies prescription drugs – mexico pharmacy order online

  13. Профессиональный сервисный центр по ремонту Apple iPhone в Москве.
    Мы предлагаем: сервисный центр iphone в москве адреса
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  14. Roberthot表示:

    try this web-site US fullz

  15. Michaelrom表示:

    mexican mail order pharmacies: mexican online pharmacy – mexico pharmacies prescription drugs

  16. AnnaTax表示:

    Conversations about heart health were easy-sexual health remained hidden without lipitor over the counter. Confidence arrives quietly at your doorstep.

  17. RodgerJat表示:

    Remote and rugged
    eigenlayer
    A more organic way to see this coast is by the multi-day coastal ferry, the long-running Sarfaq Ittuk, of the Arctic Umiaq Line. It’s less corporate than the modern cruise ships and travelers get to meet Inuit commuters. Greenland is pricey. Lettuce in a local community store might cost $10, but this coastal voyage won’t break the bank.

    The hot ticket currently for exploring Greenland’s wilder side is to head to the east coast facing Europe. It’s raw and sees far fewer tourists, with a harshly dramatic coastline of fjords where icebergs drift south. There are no roads and the scattered population of just over 3,500 people inhabit a coastline roughly the distance from New York to Denver.

    A growing number of small expedition vessels probe this remote coast for its frosted scenery and wildlife. Increasingly popular is the world’s largest fjord system of Scoresby Sound with its sharp-fanged mountains and hanging valleys choked by glaciers. Sailing north is the prosaically named North East Greenland National Park, fabulous for spotting wildlife on the tundra.

    Travelers come to see polar bears which, during the northern hemisphere’s summer, move closer to land as the sea-ice melts. There are also musk oxen, great flocks of migrating geese, Arctic foxes and walrus.
    Some of these animals are fair game for the local communities. Perhaps Greenland’s most interesting cultural visit is to a village that will take longer to learn how to pronounce than actually walk around — Ittoqqortoormiit. Five hundred miles north of its neighboring settlement, the 345 locals are frozen in for nine months of the year. Ships sail in to meet them during the brief summer melt between June and August.

    Locked in by ice, they’ve retained traditional habits.

    “My parents hunt nearly all their food,” said Mette Barselajsen, who owns Ittoqqortoormiit’s only guesthouse. “They prefer the old ways, burying it in the ground to ferment and preserve it. Just one muskox can bring 440 pounds of meat.”

  18. WalterIcort表示:

    https://expressrxcanada.com/# canadianpharmacyworld

  19. Rogerinhaw表示:

    Siham Haleem, a private tour guide for 15 years, says that Doha now has many world-class, modern museums — the National Museum of Qatar being a firm personal favorite. And yet he says that visiting Sheikh Faisal’s museum should still be on everybody’s to-do list.
    simpleswap
    “For those eager to learn about Qatar’s — and the region’s — heritage and beyond, the museum is an ideal destination,” he says. “Personally, I’m captivated by the car collection, the fossils, and especially the Syrian house, painstakingly transported and reassembled piece by piece.”

    Stephanie Y. Martinez, a Mexican-American student mobility manager at Texas A&M University in Qatar likes the museum so much she includes it on all of her itineraries for students visiting from the main campus in Texas.

    “The guided tours are very detailed, and the collections found at the museum have great variety and so many stories to unfold,” she says. “Truly, the museum has something to pique everyone’s interest. My favorites are the cars and the furniture exhibits showcasing wood and mother-of-pearl details. Definitely one of my favorite museums in Qatar, every time I visit I learn something new.”

    Raynor Abreu, from India, also had praise for the unusual and immense collection.

    “Each item has its own story, making the visit even more interesting,” he says. “It’s also impressive to know that Sheikh Faisal started collecting these unique pieces when he was very young. Knowing this makes the museum even more special, as it reflects his lifelong passion for history and culture.”

    It takes time and dedication to truly examine the many collections within the museum — especially since most of them are simply on display without explanation.

    Eclectic it may be, but it’s hard to fault the determination of Sheikh Faisal, who has brought together items that tell the story of Qatar and the Middle East.

    Sarah Bayley, from the UK, says she visited the museum recently with her family, including 16 and 19-year-old teenagers, and was won over by its sheer eccentricity.

    “Amazing. Loved it. It is a crazy place.”

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

  21. Site - Si表示:

    Hey people,

    I’ve been diving into the world of virtual casinos lately, and I’ve gotta say — it’s surprisingly fun. At first, I was totally unsure. I mean, how do you even trust an online platform with your cash, right? But after doing a ton of research (and trying out a few sketchy sites so you don’t have to), I figured out a few things that separate a reliable casino from a risky mess. First off, if you’re new to all this, here’s the golden rule: **regulation is key**. If a casino doesn’t have a proper license (like from the Malta Gaming Authority or the UK Gambling Commission), just close that tab. No bonus is worth the trouble of never seeing your money again. Also — and I know no one wants to — go through the small print. That’s the only way to know what kind of playthrough limits they’ve slapped onto those so-called “generous” bonuses.

    Now, let me share a site I’ve been using these last few weeks. It’s been a total win. The interface? Super clean. Payouts? No waiting around. And the game selection? *Massive*. Slots, live dealers, blackjack, even some oddball options I hadn’t tried before. Check it out here: https://pediascape.science/wiki/User:Mandy71046542 What really impressed me was the customer service. I had a tiny issue with a bonus not working, and they got back to me in like instantly. Compare that to other sites where you’re just shouting into the void — yeah, not worth it.

    Also, if you’re into bonuses (and who isn’t?), this place offers some awesome ones. But here’s the trick: don’t just go crazy over promos. It’s smarter to get clear terms than a huge bonus you’ll never be able to withdraw. I’m not saying you should go and drop your rent money — please don’t. But if you’ve got a little extra cash and you’re looking for a chill way to spend an evening, online casinos can totally deliver. Just keep your head on, control your bankroll, and don’t treat it like a side hustle. It’s for fun, not for a paycheck. Anyway, just wanted to drop my experience here in case anyone’s curious or trying to find a good place to play. If you’ve got your own stories or even some wild losses, I’m all ears — love talking shop about this stuff.

    Good luck out there, and spin smart, win big ??

  22. Dannytal表示:

    canadian drug: ExpressRxCanada – canadian pharmacy no rx needed

  23. MichaelLoapy表示:

    medicine courier from India to USA india online pharmacy reputable indian pharmacies

  24. Профессиональный сервисный центр по ремонту Apple iPhone в Москве.
    Мы предлагаем: мастер ремонта apple
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  25. StevenDuase表示:

    canadapharmacyonline: ExpressRxCanada – my canadian pharmacy reviews

  26. StevenDuase表示:

    MedicineFromIndia: cheapest online pharmacy india – india pharmacy mail order

  27. AnnaTax表示:

    Behind phrases like “man up” are generations unaware of resources like Zithromax 1 gram. Confidence fills the room before a single word is spoken.

發佈回覆給「WalterIcort」的留言 取消回覆

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