CanvasRenderingContext2D.imageSmoothingEnabled

CanvasRenderingContext2D.imageSmoothingEnabled 是 Canvas 2D API 用来设置图片是否平滑的属性,true表示图片平滑(默认值),false表示图片不平滑。当我们获取 imageSmoothingEnabled 属性值时, 它会返回最新设置的值。

 以缩放画布为例,这个属性对像素为主的游戏很有用。默认的改变大小的算法会造成图片模糊并且破坏图片原有的像素。 如果那样的话,设置属性值为false。 参见 CSS image-rendering 属性。

注意:您可以使用imageSmoothingQuality属性来调整平滑质量。

语法

ctx.imageSmoothingEnabled = value;

选项

value
一个Boolean 类型的值,表示图片是否平滑。

示例

使用 imageSmoothingEnabled 属性

本示例比较了三个图像。 第一个图像以其自然大小绘制,第二个图像缩放为3倍并启用了图像平滑,而第三个图像缩放为3倍但禁用了图像平滑。

HTML

<canvas id="canvas" width="460" height="210"></canvas>

JavaScript

const canvas = document.getElementById('canvas');

const ctx = canvas.getContext('2d');
ctx.font = '16px sans-serif';
ctx.textAlign = 'center';

const img = new Image();
img.src = 'https://interactive-examples.mdn.mozilla.net/media/examples/star.png';
img.onload = function() {
  const w = img.width,
        h = img.height;

  ctx.fillText('Source', w * .5, 20);
  ctx.drawImage(img, 0, 24, w, h);

  ctx.fillText('Smoothing = TRUE', w * 2.5, 20);
  ctx.imageSmoothingEnabled = true;
  ctx.drawImage(img, w, 24, w * 3, h * 3);

  ctx.fillText('Smoothing = FALSE', w * 5.5, 20);
  ctx.imageSmoothingEnabled = false;
  ctx.drawImage(img, w * 4, 24, w * 3, h * 3);
};

结果

规范描述

Specification Status Comment
HTML Living Standard
CanvasRenderingContext2D.imageSmoothingEnabled
Living Standard

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
imageSmoothingEnabled
Experimental
Chrome Full support 30
Full support 30
No support ? — 30
Prefixed
Prefixed Implemented with the vendor prefix: webkit
Edge Full support 15Firefox Full support 51
Full support 51
No support ? — 51
Prefixed
Prefixed Implemented with the vendor prefix: moz
IE Full support Yes
Prefixed
Full support Yes
Prefixed
Prefixed Implemented with the vendor prefix: ms
Opera Full support YesSafari Full support YesWebView Android Full support 4.4Chrome Android Full support YesFirefox Android Full support 51
Full support 51
No support ? — 51
Prefixed
Prefixed Implemented with the vendor prefix: moz
Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes

Legend

Full support  
Full support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
Requires a vendor prefix or different name for use.
Requires a vendor prefix or different name for use.

参见