I'm drawing a images to canvas like this:
ctx.drawImage(data[i].image, data[i].pos.x, data[i].pos.y, data[i].pos.w, data[i].pos.h);
the thing is that the picture is getting stretched and I don't want this. How I can simulate the css property
background-size: cover
while drawing image in cavas.
http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=cover
see difference between 100% 100%
(what I currently have) and cover
(my goal).
If you're looking for a simpler solution that will work for most cases, and also includes css
contain
-like functionality, try this:slightly modified version of intrinsic-scale to include scale and offset
Usage:
It's a bit more complicated to get a cover functionality, though here here is one solution for this:
Demo
Updated 2016-04-03 to address special cases. Also see @Yousef's comment below.
Now you can call it like this:
and it will scale the image proportionally to fit inside in that container.
Use the two last parameters to offset the image:
Hope this helps!