HTML5 Canvas图像缩放问题

时间:2012-05-09 22:37:25

标签: html5 html5-canvas nearest-neighbor bicubic

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

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

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

1 个答案:

答案 0 :(得分:38)

选择以下任一项:


通过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。不过,这还有很多工作要做。

相关问题