18

我正在尝试在 HTML5 画布中制作像素艺术主题游戏,作为其中的一部分,我采用 10x20 左右大小的图像并使用以下代码将它们绘制到画布上:

ctx.drawImage(image, 20, 20, 100, 200);

然而,画布使用双三次图像缩放,因此像素艺术图像在 2 倍及以上时看起来很糟糕。有没有办法强制画布使用最近邻缩放或可能使用自定义方法来缩放图像?如果不是,这是否意味着图像必须事先在 Paint.net 中进行缩放?

4

1 回答 1

40

选择以下任何一项:


通过 JavaScript:

ctx.imageSmoothingEnabled = false;

来源: http: //www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#image-smoothing

在 Gecko 上,您需要

ctx.mozImageSmoothingEnabled = false;

来源:https ://developer.mozilla.org/en/DOM/CanvasRenderingContext2D#Gecko-specific_attributes

在 Webkit 上,您需要

ctx.webkitImageSmoothingEnabled = false;

来源:https ://bugs.webkit.org/show_bug.cgi?id=82804

我在其他浏览器上找不到有关支持此属性的信息,因此它们可能不支持它。


通过 CSS:

另一种选择是在画布上使用一组 CSS 规则。例如:

<canvas id="c" width="16" height="16"></canvas>
<script>
  var c = document.getElementById("c"),
      cx = c.getContext("2d"),
      im = new Image();
  im.src = "http://stackoverflow.com/favicon.ico"; // 16x16
  cx.drawImage(im, 0, 0);
</script>
<style>
  canvas {
    width: 32px;
    height: 32px;
    image-rendering: optimizeSpeed;
    image-rendering: crisp-edges;
    image-rendering: -moz-crisp-edges;
    image-rendering: -o-crisp-edges;
    image-rendering: -webkit-optimize-contrast;
    -ms-interpolation-mode: nearest-neighbor;
  }
</style>

来源:https
://developer.mozilla.org/en/CSS/image-rendering来源:https ://bugs.webkit.org/show_bug.cgi?id=56627


通过像素例程:

另一种选择是自己使用画布像素操作例程: http: //www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#pixel-manipulation。不过,这还有很多工作要做。

于 2012-05-09T22:42:41.800 回答