帶有 image-rendering 的畫素藝術風格

本文介紹了一種在高畫質顯示器上也能讓您的 canvas/WebGL 遊戲擁有清晰畫素藝術風格的有用技術。

概念

復古 畫素藝術 美學越來越受歡迎,尤其是在 獨立遊戲遊戲製作競賽 作品中。但由於如今的螢幕以高解析度渲染內容,確保畫素藝術不顯得模糊存在一個問題。開發者一直在手動縮放大圖,以便它們顯示為代表畫素的方塊。這種方法的兩個缺點是檔案尺寸更大以及存在 壓縮偽影

small pixelated man small pixelated man larger pixelated man
原始尺寸 4 倍尺寸 4 倍尺寸(使用影像編輯器縮放)
none 廠商演算法 最近鄰插值演算法

基於 CSS 的解決方案

好訊息是,您可以使用 CSS 自動完成放大操作,這不僅解決了模糊問題,還允許您使用原始的、較小的影像尺寸,從而節省下載時間。此外,一些遊戲技術需要分析影像的演算法,使用較小的影像處理也能使這些演算法受益。

實現此縮放的 CSS 屬性是 image-rendering。實現此效果的步驟如下:

  • 建立一個 <canvas> 元素,並將其 widthheight 屬性設定為原始的、較小的解析度。
  • 將其 CSS 的 widthheight 屬性設定為 HTML widthheight 值的 2 倍或 4 倍。例如,如果 canvas 的寬度建立為 128 畫素,我們希望進行 4 倍縮放,那麼 CSS width 將設定為 512px
  • <canvas> 元素的 image-rendering CSS 屬性設定為 pixelated,這樣影像就不會模糊。還有 crisp-edges-webkit-optimize-contrast 值,它們在某些瀏覽器上有效。有關這些值之間差異以及根據瀏覽器使用哪些值的更多資訊,請參閱 image-rendering 文章。

一個例子

讓我們來看一個示例。我們想要放大的原始影像如下所示:

Pixelated night scenery of a cat on the edge off a cliff with little hearts above his head, behind him a big full moon. With a black background, white text is displayed at the bottom of the image saying: in love with the moon.

以下 HTML 程式碼用於建立一個簡單的 canvas:

html
<canvas id="game" width="128" height="128">A cat</canvas>

用於調整 canvas 大小並渲染清晰影像的 CSS

css
canvas {
  width: 512px;
  height: 512px;
  image-rendering: pixelated;
}

以及用於設定 canvas 和載入影像的一些 JavaScript:

js
// Get canvas context
const ctx = document.getElementById("game").getContext("2d");

// Load image
const image = new Image();
image.onload = () => {
  // Draw the image into the canvas
  ctx.drawImage(image, 0, 0);
};
image.src = "cat.png";

結合使用這些程式碼會產生以下結果:

注意:螢幕閱讀器無法訪問 Canvas 內容。請在 canvas 元素本身上直接包含 aria-label 屬性的描述性文字值,或在 canvas 標籤的開始和結束標籤內包含回退內容。Canvas 內容不屬於 DOM,但巢狀的回退內容屬於。