【发布时间】:2013-10-09 04:41:12
【问题描述】:
我正在尝试将 300dpi 的图像绘制到画布对象上,但在 Chrome 中它显示的质量很差。当我使用下面的代码时,它并没有改善,但那是因为devicePixelRatio 与backingStoreRatio 相同(两者都是1)。
然后我尝试强制更改一些比率并发现以下内容:
- 如果我将
ratio更改为2并强制运行缩放代码,那么它将以更好的分辨率绘制到画布上。 - 如果我将
ratio更改为大于2的任何值(例如3、4、5、6等),那么它的分辨率较差!
这一切都是在台式计算机上完成的。
如何确保画布以高分辨率绘制?
(代码来自:http://www.html5rocks.com/en/tutorials/canvas/hidpi/)
/**
* Writes an image into a canvas taking into
* account the backing store pixel ratio and
* the device pixel ratio.
*
* @author Paul Lewis
* @param {Object} opts The params for drawing an image to the canvas
*/
function drawImage(opts) {
if(!opts.canvas) {
throw("A canvas is required");
}
if(!opts.image) {
throw("Image is required");
}
// get the canvas and context
var canvas = opts.canvas,
context = canvas.getContext('2d'),
image = opts.image,
// now default all the dimension info
srcx = opts.srcx || 0,
srcy = opts.srcy || 0,
srcw = opts.srcw || image.naturalWidth,
srch = opts.srch || image.naturalHeight,
desx = opts.desx || srcx,
desy = opts.desy || srcy,
desw = opts.desw || srcw,
desh = opts.desh || srch,
auto = opts.auto,
// finally query the various pixel ratios
devicePixelRatio = window.devicePixelRatio || 1,
backingStoreRatio = context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1,
ratio = devicePixelRatio / backingStoreRatio;
// ensure we have a value set for auto.
// If auto is set to false then we
// will simply not upscale the canvas
// and the default behaviour will be maintained
if (typeof auto === 'undefined') {
auto = true;
}
// upscale the canvas if the two ratios don't match
if (auto && devicePixelRatio !== backingStoreRatio) {
var oldWidth = canvas.width;
var oldHeight = canvas.height;
canvas.width = oldWidth * ratio;
canvas.height = oldHeight * ratio;
canvas.style.width = oldWidth + 'px';
canvas.style.height = oldHeight + 'px';
// now scale the context to counter
// the fact that we've manually scaled
// our canvas element
context.scale(ratio, ratio);
}
context.drawImage(pic, srcx, srcy, srcw, srch, desx, desy, desw, desh);
}
仅进行以下更改会生成高分辨率画布图像(为什么?):
//WE FORCE RATIO TO BE 2
ratio = 2;
//WE FORCE IT TO UPSCALE (event though they're equal)
if (auto && devicePixelRatio === backingStoreRatio) {
如果我们把上面改成3的比例,就不再是高分辨率了!
编辑:另外一项观察 - 即使使用 2x 比率,虽然它的分辨率明显更好,但仍不如在 img 标签中显示图像那么清晰)
【问题讨论】:
-
@Aardvark 正如我在帖子中提到的那样,我已经尝试了该文章(HTML5Rocks)中的代码,这是该帖子所引用的,但它不起作用,因为它始终显示比率为@987654338 @,什么都不做。
-
你搞砸了 imageSmoothingEnabled 吗?
-
@Aardvark 是的,没有一个能提供更好的分辨率/清晰度/清晰度。画布无法完美再现图像。这是一种耻辱,没有任何意义。如果
img标签可以以清晰的分辨率显示图像,那么相同大小(并且具有 2 倍比例)的画布也应该能够做到。但它的锐度只有 85% 左右。
标签: javascript html google-chrome canvas html5-canvas