带有 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,但嵌套的回退内容属于。