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

  1. Georgeappox表示:

    Hidden World War II tunnels to open to public
    сколько стоять услуги адвоката в Запорожье

    In this week’s roundup of travel news: Denver’s weed church, zodiac predictions for the Year of the Snake, plus what promises to be London’s most ambitious – and deepest – new visitor attraction.

    Going underground
    Some 30 meters (98 feet) below central London lies a mile-long network of tunnels that is set to be the UK capital’s glitziest new tourist attraction, according to the company that’s secured planning approval for the $149 million transformation.

    The Kingsway Exchange Tunnels were built in the 1940s to shelter Londoners from the Blitz bombing campaign during World War II. That was the last time they were open to the general public. Their next wartime role was as the home of Britain’s top-secret Special Operations Executive, an offshoot of MI6 and the real-life inspiration for James Bond’s Q Branch.

    The new attraction will be a memorial to the Blitz, which Angus Murray, chief executive of the London Tunnels, told Reuters will be part museum, part exhibition and part entertainment space.

    The plan is to open to the public by late 2027 or early 2028. Read more here in our earlier story announcing the project.

    If you can’t wait until then to get down in the city’s bowels, London Transport Museum runs exclusive guided tours of its abandoned tube stations, including Down Street, a secret underground bunker that helped win World War II.
    Year of the Snake
    The first new moon of the lunar calendar fell on January 29, ushering in the Year of the Snake and the 15-day Spring Festival, a big annual highlight in China and for Chinese communities around the world.

    Here’s our guide to what it all means and, whether you’re a horse, goat, monkey, rooster or any other sign in the Chinese zodiac, here’s what the stars say are your predictions for the year ahead.

    Food is, of course, a key part of the celebrations. One of the most fun elements is the “prosperity toss,” kind of like a food fight with chopsticks but seasoned with auspicious blessings for the year ahead.

    For the culinarily adventurous, 2025 is a good time to visit Hong Kong and see how restaurants serve snake. Delights include snake balls and snake soup – and be sure to leave room for the penis wine. Watch here.

  2. Victorprima表示:

    Bridging continents with their top-notch service.
    can i buy generic clomid pill
    Global expertise that’s palpable with every service.

  3. But as an alternative of breaking into the first-workforce like Rashford and other winners akin to Mason Greenwood, Alejandro Garnacho and Kobbie Mainoo, his progress slowed after making a senior debut in its place for Wayne Rooney on the final day of the 2016-17 season.

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

  5. Jasonzitte表示:

    A gem in our community.
    gabapentin capsules 300 mg
    A pharmacy that feels like family.

  6. Victorprima表示:

    Their loyalty points system offers great savings.
    can i get cipro for sale
    The go-to place for all my healthcare needs.

  7. Jorgeham表示:

    ак заказать продвижение сайта и понять цену?
    В прошлом посте мы рассказали, почему продвижение сайта в топ Yandex важно для вашего бизнеса. Сегодня разберём, как заказать продвижение сайта у SMM Portable и что влияет на цену услуги. Этот пост поможет вам освоить процесс и выбрать лучший план для раскрутки сайта.
    Как заказать SEO-услуги?
    Процесс заказа прост и включает три шага:
    Связаться с нами: Напишите нам в Telegram или заполните форму на сайте SMM Portable.
    фирма по созданию и продвижению сайтов
    Предоставить информацию: Укажите URL сайта, целевые запросы (например, “купить мебель в Москве”) и цели бизнеса.

    Консультация и анализ: Мы проведём аудит вашего сайта, оценим конкурентов и предложим стратегию продвижения.
    После этого мы берём всё в свои руки, чтобы ваш сайт начал привлекать больше клиентов.
    Как формируется цена?
    Стоимость SEO зависит от нескольких факторов:
    Уровень конкуренции: Высококонкурентные ниши (например, недвижимость) требуют больше ресурсов.

    Состояние сайта: Новый сайт или сайт с ошибками нуждается в дополнительной оптимизации.

    Ключевые запросы: Продвижение по популярным словам дороже, чем по узким запросам.
    Примерные цены:
    Для малого бизнеса (локальные запросы): от 50 000 руб./мес.

    Для интернет-магазина (средняя конкуренция): от 100 000 руб./мес.

    Для крупных проектов (высокая конкуренция): от 500 000 руб./мес.
    В эти суммы входят аудит, создание контента, работа со ссылками и техническая оптимизация.
    Почему стоит выбрать SMM Portable?
    Экспертиза в Yandex: Мы знаем, как работают алгоритмы 2025 года, и используем это для ваших результатов.

    Долгосрочный эффект: Наша цель — устойчивый рост, а не временные позиции.

    Успешные кейсы: Например, стоматология в Москве поднялась в топ-5 за полгода, увеличив трафик на 200%.
    Начните прямо сейчас!
    Заказать продвижение сайта проще простого: свяжитесь с нами, и мы подготовим для вас план и точную цену. В следующем посте расскажем о продвинутых методах раскрутки сайта. Подписывайтесь на SMM Portable, чтобы не пропустить!

  8. However, rarer turquoise, akin to Lander Blue Spider Web, can sell for $300 per carat or $1,500 per gram!

  9. 1win_vner表示:

    1win букмекер [url=http://aqvakr.forum24.ru/?1-3-0-00001121-000-0-0/]1win букмекер[/url] .

  10. DonaldTyclE表示:

    Espectro de vibracion
    Equipos de equilibrado: esencial para el operacion fluido y eficiente de las maquinarias.

    En el ambito de la ciencia avanzada, donde la efectividad y la estabilidad del sistema son de maxima relevancia, los equipos de equilibrado cumplen un tarea esencial. Estos equipos especificos estan desarrollados para balancear y estabilizar partes moviles, ya sea en herramientas productiva, automoviles de traslado o incluso en aparatos domesticos.

    Para los tecnicos en mantenimiento de equipos y los tecnicos, trabajar con sistemas de equilibrado es crucial para proteger el desempeno estable y estable de cualquier sistema movil. Gracias a estas soluciones modernas sofisticadas, es posible limitar sustancialmente las vibraciones, el zumbido y la esfuerzo sobre los soportes, mejorando la vida util de piezas importantes.

    Igualmente trascendental es el papel que juegan los dispositivos de calibracion en la soporte al comprador. El asistencia especializado y el reparacion constante usando estos aparatos habilitan dar prestaciones de alta nivel, incrementando la bienestar de los compradores.

    Para los responsables de emprendimientos, la aporte en unidades de balanceo y detectores puede ser clave para aumentar la productividad y productividad de sus aparatos. Esto es especialmente importante para los inversores que manejan pequenas y medianas empresas, donde cada aspecto importa.

    Asimismo, los equipos de calibracion tienen una gran aplicacion en el ambito de la fiabilidad y el monitoreo de nivel. Facilitan localizar posibles fallos, evitando mantenimientos caras y danos a los aparatos. Incluso, los resultados generados de estos sistemas pueden utilizarse para perfeccionar sistemas y incrementar la visibilidad en buscadores de investigacion.

    Las sectores de utilizacion de los equipos de balanceo incluyen multiples sectores, desde la fabricacion de vehiculos de dos ruedas hasta el monitoreo del medio ambiente. No afecta si se trata de enormes manufacturas manufactureras o reducidos talleres domesticos, los aparatos de calibracion son necesarios para proteger un funcionamiento efectivo y sin presencia de detenciones.

  11. mostbet_uvOr表示:

    мост бет [url=https://www.chesskomi.borda.ru/?1-10-0-00000277-000-0-0-1741171219]мост бет[/url] .

  12. Jasonzitte表示:

    They always have valuable advice on medication management.
    can i purchase generic lisinopril for sale
    They’re at the forefront of international pharmaceutical innovations.

  13. WalterCherm表示:

    Been a loyal customer for years and they’ve never let me down.
    https://clomidpharm24.top/
    Their adherence to safety protocols is commendable.

  14. 1win_cmma表示:

    1вин кыргызстан [url=www.cah.forum24.ru/?1-13-0-00001560-000-0-0-1741172791]www.cah.forum24.ru/?1-13-0-00001560-000-0-0-1741172791[/url] .

  15. Louisembap表示:

    How the Business Model of an SEO Company Works
    читать
    While some marketing agencies provide a wide array of services, an SEO company generally focuses its expertise on organic ranking improvements. Their business model can include a monthly retainer, one-time project fees, or performance-based pricing. In the monthly retainer model, the SEO company devotes ongoing resources to adjust strategies, produce new content, and monitor keyword performance. A one-time project might be a large-scale technical overhaul or a complete content revamp. Performance-based pricing, less common but still seen in some arrangements, involves compensation tied to achieving specific milestones like page-one rankings for defined keywords. Regardless of the payment structure, the guiding principle is to consistently enhance the client’s online visibility and measure success through quantifiable data.

  16. 1win_zter表示:

    1вин официальный сайт aqvakr.forum24.ru/?1-3-0-00001121-000-0-0 .

  17. Jasonzitte表示:

    The staff exudes professionalism and care.
    buy generic cytotec for sale
    The pharmacists are always updated with the latest in medicine.

  18. Mike Tyson fue el campeón más joven en la historia del peso pesado | Los documentales sobre Mike Tyson revelan detalles sorprendentes de su vida | Los seguidores de Mike Tyson esperan con ansias su nuevo combate | El impacto de Mike Tyson en la cultura popular es impresionante Mike Tyson campeón .

  19. situs togel表示:

    Untuk memperoleh kemenangan terbesar pemain harus mampu dalam mengenal situs togel online dengan memasangkan angka taruhan akurat bayaran uang asli.

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

  21. Victorprima表示:

    They have strong partnerships with pharmacies around the world.
    where can i get cheap cipro tablets
    The pharmacists are always updated with the latest in medicine.

  22. lottery 66表示:

    Try 66lottery now

  23. JamesFrito表示:

    Накрутка поведенческих факторов для поисковых систем: что это и как с ней бороться
    тут
    В поисковом продвижении (SEO) очень часто говорят о поведенческих факторах: время, проведённое пользователем на сайте, глубина просмотра, процент отказов, кликабельность в результатах выдачи (CTR) и многое другое. Эти показатели активно используются поисковыми системами, такими как Яндекс или Google, для оценки релевантности и качества веб-ресурсов. Чем лучше пользовательский опыт, тем выше сайт может подняться в поисковой выдаче по определённым запросам. Однако некоторые веб-мастера или владельцы сайтов решаются на «обман системы» — так называемую «накрутку поведенческих факторов». Под ней понимают искусственное повышение (или понижение) значений важных метрик, чтобы выглядеть более привлекательным для алгоритмов поиска и занять высокие позиции в SERP.

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

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