canvas图像质量问题

我试图模拟canvas中的background-size: cover属性。 我得到了它的工作,但质量很差。

这是一个小提琴 。 你可以比较这两个图像(缩小,所以你可以看到两个图像相邻):

我的代码如下所示:

 function drawImageProp(ctx, img, x, y, w, h, offsetY) { var iw = img.width, ih = img.height, r = Math.min(w / iw, h / ih), newW = iw * r, newH = ih * r, cx, cy, cw, ch, ar = 1; if (newW < w) ar = w / newW; if (newH < h) ar = h / newH; newW *= ar; newH *= ar; cw = iw / (newW / w); ch = ih / (newH / h); cy = -parseInt(offsetY) * ih / newH; ctx.patternQuality = 'best'; ctx.antialias = 'default'; ctx.filter = 'default'; ctx.drawImage(img, 0, cy, cw, ch, x, y, w, h); 

我试过添加

 ctx.patternQuality = 'best'; ctx.antialias = 'default'; ctx.filter = 'default'; 

为了提高质量,但我还没有得到足够好的质量。 是否有可能在canvas中使用原始的质量图像。

同样parseInt(x)parseInt(x) + 0.5parseInt(x) + 0.5 ,没有解决问题。

* 这个问题被标记为nodejs因为我在nodejs中使用了这个代码和node-canvas模块。

尝试在上下文中将imageSmoothingEnabled属性设置为false:

 ctx.imageSmoothingEnabled = false; 

缩放时,默认使用双线性filter进行canvas。 这是模糊的。 您可能需要最近邻居过滤,这只是一个像素重复。