0

I know I can draw the whole image on canvas using:

ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);

but this will mess up the image on certain screens. I want to draw the image as it would have appeared on a div with background-size: cover applied. Is it possible at all?

This question answered the background-size: cover part. I want to figure out how to simulate background-position: 100% 100% now. In other words, I want to draw the bottom right of image in the bottom right part of canvas. How can I do that?

Neena Vivek
  • 667
  • 7
  • 19
  • 1
    Possible duplicate of [Simulation background-size: cover in canvas](http://stackoverflow.com/questions/21961839/simulation-background-size-cover-in-canvas) and some more complete aspect ratio Q/A : http://stackoverflow.com/questions/34428723/how-to-implement-svgs-preserveaspectratio-xminymin-slice-for-canvas-drawimage/34429774#34429774 – Kaiido Nov 03 '16 at 04:34
  • while drawing image in cavas. , how you are getting the image – Purushothaman Nov 03 '16 at 04:39
  • @Purushothaman why CSS tag ? OP is not asking for a CSS solution, but just to reproduce the result of it. People with knowledge about CSS won't help so much in here. – Kaiido Nov 03 '16 at 04:44
  • @Kaiido thanks for the link to question, I still need to figure out how to draw the bottom right part of image at the bottom right of canvas. I am not asking for complete solution but only for pointing me in the right direction. :) – Neena Vivek Nov 03 '16 at 04:48
  • @NeenaVivek, next time, please go directly to the point, it is kind of arsh to find you a correct answer just before you decide to modify your question entirely. For background-position 100% 100% just do `drawImage(img, canvas.width - img.width, canvas.height - img.height)` – Kaiido Nov 03 '16 at 04:50
  • @Kaiido I tried both `drawImageProp(ctx,img,canvas.width - img.width, canvas.height - img.height,window.innerWidth,window.innerHeight,0,0,0,0);` and `ctx.drawImage(img, canvas.width - img.width, canvas.height - img.height, cw, ch, x, y, w, h);` None of them drew the image at all. There was no error in the console though. – Neena Vivek Nov 03 '16 at 04:58
  • Because you want both the cover and the position 100% ? I gave you only the position 100%. If you need to change the position of the cover one, in K3n's answer there is an offsetX and offsetY option, set it to the canvas width and height : http://jsfiddle.net/bu30sfya/ In my SVG like answer, set the string to `xMaxYMax slice` – Kaiido Nov 03 '16 at 05:06

0 Answers0