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...

17,940 Responses

  1. mostbet表示:

    An outstandingly text is shaping up to be remarkable, and I acknowledge the understanding and accuracy of your evaluation. It engaged me beyond words. Your talent in depicting varied concepts with extraordinary articulateness is respectable. Furthermore, your position on pressing issues furnishes informative examination. Your imaginative method and considerable perception of nuanced subjects are apparent in every word of your work. I await discovering more of your commentaries in the approaching days.

    read more here

  2. WilliamTic表示:

    В нашем мире, где аттестат является началом удачной карьеры в любой сфере, многие ищут максимально быстрый путь получения качественного образования. Важность наличия документа об образовании сложно переоценить. Ведь диплом открывает дверь перед любым человеком, который собирается вступить в профессиональное сообщество или учиться в каком-либо институте.
    В данном контексте наша компания предлагает оперативно получить этот необходимый документ. Вы имеете возможность купить аттестат, и это будет отличным решением для человека, который не смог закончить обучение, потерял документ или хочет исправить плохие оценки. Аттестаты изготавливаются аккуратно, с максимальным вниманием ко всем нюансам. В результате вы сможете получить продукт, полностью соответствующий оригиналу.
    Превосходство этого решения состоит не только в том, что вы оперативно получите аттестат. Процесс организовывается просто и легко, с нашей поддержкой. От выбора требуемого образца документа до консультации по заполнению личных данных и доставки в любое место России — все находится под абсолютным контролем квалифицированных мастеров.
    В результате, для тех, кто ищет оперативный способ получения необходимого документа, наша компания предлагает отличное решение. Купить аттестат – это значит избежать продолжительного обучения и не теряя времени перейти к достижению своих целей, будь то поступление в университет или старт карьеры.

    https://kgufkst.ru/structure/biblioteka/informatsionnye-obrazovatelnye-nauchnye-i-sportivnye-sayty/

  3. Such a piece is regarded as excellent, and I praise the wisdom and relevance of your narrative. It inspired me in so many ways. Your craft in articulating multifaceted concepts with outstanding precision is remarkable. Furthermore, your approach on crucial issues offers in-depth review. Your innovative style and profound cognition of multifaceted subjects are evident in every passage of your writing. I anticipate discovering more of your pieces in the time to come.

    mostbet

  4. This essay stands out as informative, and I appreciate the perspective and quality of your writing. It inspired me deeply. Your competence in illustrating detailed concepts with remarkable simplicity is praiseworthy. Furthermore, your perspective on important issues delivers enlightening assessment. Your unique methodology and far-reaching perception of intricate subjects stand out in every word of your production. I await witnessing more of your pieces in the approaching days.

    mostbet login download

  5. Mostbet表示:

    Your exposition is shaping up to be outstanding, and I appreciate the insight and quality of your research. It moved me like never before. Your artistry in expressing sophisticated concepts with amazing coherence is exceptional. Furthermore, your stance on urgent issues furnishes detailed discussion. Your visionary manner and vast knowledge of challenging subjects are unmistakable in every line of your composition. I await perusing more of your pieces in the near future.

    mostbet.com

  6. website link表示:

    An impressively work is regarded as outstanding, and I commend the understanding and originality of your perspective. It touched me like never before. Your talent in illustrating diverse concepts with such precision is noteworthy. Furthermore, your opinion on pressing issues provides informative analysis. Your imaginative way and comprehensive intuition of nuanced subjects stand out in every paragraph of your piece. I am keen on observing more of your commentaries in the coming times.

    mostbet.com

  7. mostbet表示:

    A uniquely essay stands out as excellent, and I cherish the understanding and substance of your writing. It motivated me immensely. Your expertise in expressing varied concepts with unparalleled coherence is impressive. Furthermore, your stance on pressing issues presents in-depth exploration. Your inspired way and deep understanding of challenging subjects are evident in every word of your endeavor. I eagerly await experiencing more of your content in the days ahead.

    mostbet apk download

  8. mostbet.com表示:

    This text is considered to be incredible, and I value the comprehensiveness and significance of your evaluation. It challenged me significantly. Your proficiency in depicting diverse concepts with amazing fluency is admirable. Furthermore, your standpoint on crucial issues presents detailed discussion. Your inventive strategy and substantial understanding of multifaceted subjects are prominent in every phrase of your opus. I am keen on perusing more of your content in the time to come.

    mostbet official app

  9. link url表示:

    I’d have to verify with you here. Which is not something I usually do! I get pleasure from studying a publish that can make people think. Additionally, thanks for allowing me to remark!

  10. An outstandingly piece has been educational, and I admire the information and originality of your arguments. It moved me greatly. Your craft in explaining varied concepts with outstanding coherence is remarkable. Furthermore, your position on vital issues provides enriching exploration. Your visionary strategy and substantial comprehension of demanding subjects stand out in every sentence of your piece. I eagerly await seeing more of your content in the forthcoming period.

    mostbet app

  11. mostbet.com表示:

    An outstandingly content stands out as educational, and I cherish the understanding and quality of your analysis. It enlightened me in so many ways. Your mastery in portraying detailed concepts with astonishing clarity is exceptional. Furthermore, your approach on urgent issues provides much-needed study. Your inspired manner and far-reaching perception of demanding subjects are evident in every part of your creation. I can’t wait for seeing more of your posts in the next days.

    mostbet.com

  12. Most Bet表示:

    An incredibly exposition stands out as incredible, and I esteem the perspective and richness of your explanation. It informed me in a unique way. Your artistry in portraying nuanced concepts with astonishing accuracy is outstanding. Furthermore, your stance on vital issues supplies detailed exploration. Your unique method and intense perception of complicated subjects are evident in every segment of your opus. I eagerly await reading more of your writing in the next days.

    mostbet app download apk

  13. mostbet.com表示:

    A deeply essay is educational, and I admire the wisdom and relevance of your evaluation. It stimulated me like never before. Your proficiency in portraying nuanced concepts with remarkable simplicity is remarkable. Furthermore, your standpoint on crucial issues yields thoughtful study. Your original method and far-reaching knowledge of multifaceted subjects shine through in every line of your piece. I look forward to reading more of your reviews in the days ahead.

    you could look here

  14. Most Bet表示:

    A deeply writing is considered to be outstanding, and I admire the knowledge and significance of your analysis. It inspired me in a unique way. Your proficiency in articulating complicated concepts with unparalleled ease is impressive. Furthermore, your approach on important issues yields enlightening examination. Your groundbreaking style and far-reaching comprehension of complex subjects are noticeable in every part of your output. I anticipate absorbing more of your reviews in the time to come.

    mostbet

  15. Excelente cassino para ganhos Blaze

  16. Tente sua sorte no melhor cassino Blaze

  17. The effort you’ve put into this post is evident and much appreciated. It’s clear you care deeply about The work.

  18. Max Maury表示:

    The writing is a masterpiece. You managed to cover every aspect with such finesse.

  19. Daysi Croshaw表示:

    Articulated points with finesse, like a lawyer, but without the billable hours.

  20. The effort you’ve put into this post is evident and much appreciated. It’s clear you care deeply about The work.

  21. Roger Deval表示:

    The posts are like a secret garden of knowledge. I’m always excited to see what’s blooming.

  22. Marnie Werra表示:

    The fresh insights were a breath of fresh air. Thank you for sharing The unique perspective.

  23. O lugar perfeito para jogos de azar Blaze

  24. O melhor cassino on-line para voce Blaze

  25. Отличный сайт! Всем рекомендую!охотничий магазин

  26. Jamesceaph表示:

    Читайте интересные статьи на актуальные темы, связанные с покупкой жилья, например приемка квартиры в новостройке или стоимость недвижимости в Москве.
    Сайт: https://ooo-trotuar.ru

  27. MichaelReush表示:

    Псс… Полезные статьи о недвижимости. Аренда, купля/продажа, недвижимость как бизнес. Подробнее http://sma-repair.ru

  28. DanielGed表示:

    1xBet free promo code: 1XBOX777, get vip sports bonus of 100% up to €/$130 (or the equivalent in your local currency). Our website is a treasure trove of the most up-to-date promotions and bonus codes for the year 2024. Moreover, when you register at 1xBet casino using this bonus code, you’ll be greeted with a welcome bonus of €/$1950 and 150 free spins. These incredible bonuses enhance every new player’s winning potential, allowing them to indulge in thrilling gameplay with bonus funds.

  29. JosephGed表示:

    Unlock More Exciting Promotions at 1xBet India
    1xBet free bet promo code: 1XBOX777. Sign up and receive a 100% bonus up to €100 in free bets. 1xBet is a reliable bookmaker that is committed to building a long-term relationship with every customer. We guarantee a personalized approach in your best interest, easy payment methods, and most importantly, 100% payouts on all winning bets. 1xBet India doesn’t stop at the welcome bonuses. There are several other enticing promotions available for Indian customers to enhance their gaming experience. Take a look at these ongoing promotions:

    Lucky Friday: Every Friday, 1xBet India offers a bonus of up to 100€. To claim this bonus, simply log in to your 1xBet account, deposit any amount (minimum €1), and ensure your account is active. The bonus will be automatically credited, matching 100% of your deposit amount, up to €100. To receive the bonus, you must wager the bonus amount three times on accumulator bets within 24 hours. Make sure to review the full terms and conditions before participating.

    x2 Wednesday Promotion: On Wednesdays, while the promotion is active, 1xBet offers a bonus of up to 100€. To qualify, you need to have participated in the “Lucky Friday” offer the week before and redeemed your bonus. Log in to your 1xBet account and place five bets on any sporting event on Monday and Tuesday with minimum odds of 1.40. Additionally, make a deposit of up to €100 on Wednesday. The bonus will be credited automatically, matching 100% of your deposit amount, up to €100. To redeem the bonus, you must meet the 3x wagering requirements through accumulator bets within 24 hours. Familiarize yourself with the terms and conditions before participating.

    1xBet promo code casino: 1XBOX777, allows you to benefit from a 100% increase in the 1xBet casino welcome package of ?130,000. This implies that you can receive up to ?169,000 in total through four separate deposits. By signing up with this promotional code, you are ensuring an improved betting experience on 1xBet. 1xBet is a reputable and renowned bookmaker that provides a diverse selection of sports betting opportunities and enticing promotions for the year 2024.

    On the platform, you will find a diverse selection of sports to bet on, including football, tennis, basketball, and more. With competitive odds and favorable betting conditions, you can increase your chances of success and make your time on the platform even more thrilling. Additionally, you will receive €100 in free bets, which will further enhance your betting opportunities.

    1xBet is a trusted bookmaker that is known for its reliability and excellent customer service. By taking advantage of this promo code, you can enjoy the excitement of free betting without any initial risk. Don’t miss out on this opportunity to maximize your winnings and enjoy a top-notch betting experience on 1xBet.

    Don’t miss out on this incredible opportunity. Claim your share of up to €100 in free bets today by registering on 1xBet with the 1xBet promo code free. Start your betting journey with confidence and excitement, backed by an outstanding bonus offer tailored just for you.
    A more detailed description of how to correctly use a promotional code when registering with 1xBet — https://www.meyermachine.com/wp-content/pgs/1xbet_promo_code____388.html

  30. гейтс оф олимпус играть гейтс оф олимпус играть .

發佈留言

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