CanvasRenderingContext2D:imageSmoothingEnabled 屬性

Baseline 已廣泛支援

該特性已非常成熟,可在多種裝置和瀏覽器版本上使用。自 2017 年 4 月以來,它已在各大瀏覽器上可用。

CanvasRenderingContext2D 介面的 imageSmoothingEnabled 屬性是 Canvas API 的一部分,它決定了縮放後的影像是否會被平滑處理(true,預設值)或不被平滑處理(false)。獲取 imageSmoothingEnabled 屬性時,會返回上次設定給它的值。

此屬性對於使用畫素藝術的遊戲和其他應用程式很有用。放大影像時,預設的縮放演算法會模糊畫素。將此屬性設定為 false 以保持畫素的銳利度。

注意:您可以使用 imageSmoothingQuality 屬性調整平滑質量。

一個布林值,指示是否平滑縮放的影像。預設值為 true

示例

停用影像平滑

此示例比較了三張影像。第一張影像以其原始尺寸繪製,第二張影像放大到 3 倍並啟用了影像平滑,第三張影像放大到 3 倍但停用了影像平滑。

HTML

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

JavaScript

js
const canvas = document.getElementById("canvas");

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

const img = new Image();
img.src = "/shared-assets/images/examples/big-star.png";
img.onload = () => {
  const w = img.width,
    h = img.height;

  ctx.fillText("Source", w * 0.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);
};

結果

規範

規範
HTML
# dom-context-2d-imagesmoothingenabled-dev

瀏覽器相容性

另見