I'm trying to simulate the background-size: cover
property in canvas. I got it working, but the quality is bad.
Here is a fiddle. You can compare the two images(zoom out so you can see both image next to each other):
My code looks like:
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);
I've tried adding
ctx.patternQuality = 'best';
ctx.antialias = 'default';
ctx.filter = 'default';
in order to improve quality, but I'm still no getting enough good quality. Is it possible to use the original quality image in canvas.
Also parseInt(x)
and parseInt(x) + 0.5
to the cordinates, didn't fixed the problem.
*This question is tagged with nodejs
because I'm using this code in nodejs with the node-canvas module.