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

  1. Cazrtvb表示:

    Где купить диплом специалиста?
    Мы изготавливаем дипломы психологов, юристов, экономистов и других профессий по невысоким ценам. Важно, чтобы дипломы были доступными для большого количества граждан. Приобрести диплом об образовании diplomt-v-samare.ru/kupit-diplom-vuza-s-provodkoj-v-reestr-bistro-i-nadezhno-2/

  2. KennethKex表示:

    вавада: вавада официальный сайт – vavada

  3. 1win_iaEl表示:

    lucky jet коэффициенты http://1win10001.ru .

  4. KennethKex表示:

    pin-up casino giris: pin-up casino giris – pin up az

  5. WilliamNug表示:

    New design revealed for Airbus hydrogen plane
    renzo

    In travel news this week: Bhutan’s spectacular new airport, the world’s first 3D-printed train station has been built in Japan, plus new designs for Airbus’ zero-emission aircraft and France’s next-generation high-speed trains.

    Grand designs
    European aerospace giant Airbus has revealed a new design for its upcoming fully electric, hydrogen-powered ZEROe aircraft. powered by hydrogen fuel cells.

    The single-aisle plane now has four engines, rather than six, each powered by their own fuel cell stack.

    The reworked design comes after the news that the ZEROe will be in our skies later than Airbus hoped.

    The plan was to launch a zero-emission aircraft by 2035, but now the next-generation single-aisle aircraft is slated to enter service in the second half of the 2030s.

    Over in Asia, the Himalayan country of Bhutan is building a gloriously Zen-like new airport befitting a nation with its very own happiness index.

    Gelephu International is designed to serve a brand new “mindfulness city,” planned for southern Bhutan, near its border with India.

    In rail travel, Japan has just built the world’s first 3D-printed train station, which took just two and a half hours to construct, according to The Japan Times. That’s even shorter than the whizzy six hours it was projected to take.

    France’s high-speed TGV rail service has revealed its next generation of trains, which will be capable of reaching speeds of up to 320 kilometers an hour (nearly 200 mph).

    The stylish interiors have been causing a stir online, as has the double-decker dining car.

    Finally, work is underway in London on turning a mile-long series of secret World War II tunnels under a tube station into a major new tourist attraction. CNN took a look inside.

  6. USATax表示:

    Many men report renewed interest in intimacy and connection after starting treatment with fildena super active отзывы. You don’t chase the moment – you create it.

  7. USATax表示:

    “He said healing looks different for everyone. For me, it began with cialis daily. Every strong result begins with the right dose designed just for you.

  8. Richardfek表示:

    pin up azerbaycan pin up azerbaycan pin up azerbaycan

  9. Jasontep表示:

    Water and life
    stargate finance
    Lightning is a dramatic display of electrical power, but it is also sporadic and unpredictable. Even on a volatile Earth billions of years ago, lightning may have been too infrequent to produce amino acids in quantities sufficient for life — a fact that has cast doubt on such theories in the past, Zare said.

    Water spray, however, would have been more common than lightning. A more likely scenario is that mist-generated microlightning constantly zapped amino acids into existence from pools and puddles, where the molecules could accumulate and form more complex molecules, eventually leading to the evolution of life.

    “Microdischarges between obviously charged water microdroplets make all the organic molecules observed previously in the Miller-Urey experiment,” Zare said. “We propose that this is a new mechanism for the prebiotic synthesis of molecules that constitute the building blocks of life.”

    However, even with the new findings about microlightning, questions remain about life’s origins, he added. While some scientists support the notion of electrically charged beginnings for life’s earliest building blocks, an alternative abiogenesis hypothesis proposes that Earth’s first amino acids were cooked up around hydrothermal vents on the seafloor, produced by a combination of seawater, hydrogen-rich fluids and extreme pressure.

    Researchers identified salt minerals in the Bennu samples that were deposited as a result of brine evaporation from the asteroid’s parent body. In particular, they found a number of sodium salts, such as the needles of hydrated sodium carbonate highlighted in purple in this false-colored image – salts that could easily have been compromised if the samples had been exposed to water in Earth’s atmosphere.

    Related article
    Yet another hypothesis suggests that organic molecules didn’t originate on Earth at all. Rather, they formed in space and were carried here by comets or fragments of asteroids, a process known as panspermia.

    “We still don’t know the answer to this question,” Zare said. “But I think we’re closer to understanding something more about what could have happened.”

    Though the details of life’s origins on Earth may never be fully explained, “this study provides another avenue for the formation of molecules crucial to the origin of life,” Williams said. “Water is a ubiquitous aspect of our world, giving rise to the moniker ‘Blue Marble’ to describe the Earth from space. Perhaps the falling of water, the most crucial element that sustains us, also played a greater role in the origin of life on Earth than we previously recognized.”

  10. JoshuaTic表示:

    Compound Finance is redefining decentralized finance! With powerful Compound DeFi tools, competitive Compound interest rates, and reliable Compound APY, it’s a go-to for crypto users everywhere. Whether you’re staking COMP token, using Compound Finance wallet, or exploring Compound alternatives, this platform has it all. Need guidance? The Compound Finance tutorial makes it easy, and every Compound Finance review proves its value. From Compound lending to Compound borrowing, it’s built on the trusted Compound protocol. Compound where to start? Visit http://compound.ad and join the Compound crypto revolution today!

  11. ZackaryGer表示:

    https://vavadavhod.tech/# вавада официальный сайт

  12. Elmerbuils表示:

    pin up вход: пинап казино – пин ап вход

  13. Zacharydorne表示:

    Наркологическая клиника «Эдельвейс» в Екатеринбурге специализируется на оказании оперативной и квалифицированной помощи при снятии ломки. Наши специалисты обладают многолетним опытом работы и применяют современные методики для безопасного и эффективного лечения абстинентного синдрома. Мы работаем круглосуточно, что позволяет оказывать помощь в любое время суток, обеспечивая анонимность и конфиденциальность каждого пациента.
    Подробнее тут – снятие ломки на дому цена

  14. Marcelohyday表示:

    лазерная эпиляция всего тела лазерная эпиляция лица

  15. RonnieAnogy表示:

    отоларинголог центр https://lor-otolaringolog-abakan.ru

  16. Marcelohyday表示:

    лазерная эпиляция зоны виды лазерной эпиляции

  17. 1win_zwOt表示:

    1вин промокод https://1win8004.ru .

  18. 1win_rjOt表示:

    1win как использовать бонус казино http://1win8004.ru/ .

  19. JamesWeent表示:

    косметолог клиника косметолог клиника

  20. Richardfek表示:

    pin-up pin up casino pin-up

  21. ZackaryGer表示:

    https://vavadavhod.tech/# вавада официальный сайт

  22. Richardfek表示:

    пин ап зеркало пин ап зеркало пин ап вход

  23. KennethTwisa表示:

    Challenging our perceptions of ‘perfection’
    traderjoexyz exchange
    With health influencers raising the bar for success, the wellness space now often feels like a performative space where people strive to showcase peak physical and mental strength.

    While seeing others’ achievements can be motivating, it can also be discouraging if your progress doesn’t match theirs.

    Each person is chasing the perfect version of themselves — whether it’s a body or a lifestyle — which is dangerous because this is typically an impossible or dangerous version to achieve, Curran said. He added that this type of comparison creates a dangerous cycle in which people constantly feel dissatisfied with their own progress.

    “It’s a fantasy in many ways, and once you start chasing after it, you constantly find yourself embroiled in a sense of doubt and deficit,” he said.

    Curran also noted that wellness challenges can be particularly damaging for women who struggle with perfectionism, as they tend to be bombarded with impossible beauty standards and societal expectations.

    Renee McGregor, a UK-based dietitian who specializes in eating disorders and athlete performance, encourages people to approach wellness trends with curiosity and skepticism. That’s because some influencers and celebrities could be promoting products because there’s a financial benefit for them.

    “The thing to ask yourself about the person you’re taking advice from is what do they gain from it?” McGregor said. “If they are going to gain financially, then you know that they (could be willing) to sell you a lie.”
    Whether you want to try a new challenge or product that promises amazing results, McGregor suggests doing your research and seeking diverse perspectives, including consulting with doctors when possible.

  24. Zazactus表示:

    маркетплейс аккаунтов соцсетей купить аккаунт

  25. KennethKex表示:

    pin up azerbaycan: pin up casino – pin up

  26. AnnaTax表示:

    He thought I’d leave if it happened again-but I stayed, and we found clomid price. Every small choice creates a future filled with greater confidence.

發佈留言

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