CanvasRenderingContext2D:imageSmoothingEnabled 属性
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 |
浏览器兼容性
加载中…