调整画布图像的大小而不会使其模糊 [英] Resizing a canvas image without blurring it

查看:201
本文介绍了调整画布图像的大小而不会使其模糊的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小图片,我在画布上渲染,如下所示:

I have a small image, which I am rendering on a canvas, like this:

ctx.drawImage(img, 0, 0, img.width*2, img.height*2);

我希望这能显示一个急剧增大的图像(每个图像像素有4个相同的像素)。但是,此代码(在Mac上的Chrome 29中)会产生模糊的图像。在Photoshop术语中,看起来它使用的是Bicubic重新取样,而不是最近邻。

I would like this to show a sharp upsized image (4 identical pixels for each image pixel). However, this code (in Chrome 29 on Mac) makes a blurry image. In Photoshop terms, it looks like it's using "Bicubic" resampling, instead of "Nearest Neighbour".

在有用的情况下(例如复古游戏) ),是否有可能产生一个急剧增大的图像,或者我是否需要为服务器上的每个图像大小分别创建一个图像文件?

In a situation where it would be useful (eg. a retro game), Is it possible to produce a sharp upsized image, or do I need to have a seperate image file for each size of the image on the server?

推荐答案

只需关闭画布'抗锯齿图片 - 遗憾的是这个属性仍然以供应商为前缀,所以这里有变化:

Simply turn off canvas' anti-aliasing for images - unfortunately this property is still vendor prefixed so here are the variations:

context.webkitImageSmoothingEnabled = false;
context.mozImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false; /// future

然后绘制图像。

对于尚未实现此功能的旧版本和浏览器,您可以选择使用CSS:

Optionally for older versions and browsers which hasn't implemented this yet, you can use CSS instead:

canvas {
    image-rendering: optimizeSpeed;             // Older versions of FF
    image-rendering: -moz-crisp-edges;          // FF 6.0+
    image-rendering: -webkit-optimize-contrast; // Webkit (non standard naming)
    image-rendering: -o-crisp-edges;            // OS X & Windows Opera (12.02+)
    image-rendering: crisp-edges;               // Possible future browsers.
    -ms-interpolation-mode: nearest-neighbor;   // IE (non standard naming)
}

在线测试

ONLINE TEST HERE

这篇关于调整画布图像的大小而不会使其模糊的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆