0

I have an image which has a ratio of 1724:1078(width:height). Now i need to center that image inside canvas which is 800:1078. This scenario works perfect with the code bellow:

ctx.drawImage(this.leftImageResized, ((this.thumbnailWidth/2)-this.leftImageResized.width)/2, (this.thumbnailHeight-this.leftImageResized.height)/2);

But what i cannot figure out is how to position the image to the left of the canvas and to the right of the canvas, because the image is wider than the canvas itself. What i basically need to achieve is placing the left side of the image in the beginning of the canvas and in the second scenario placing the right side of the image to the right side of the canvas. I already tried the code bellow to position it to the left:

  ctx.drawImage(this.leftImageResized, 0, 0);

But this code does not work as expected. Basically it crops out a part of the image, although the image is positioned to the left a part of the image to the left is outside of view...

EDIT: This question has not a single point common with the question pointed as a duplicate, i am not simulating a cover at all, at the contrary my image should be cut but in different context. As you can see on the image bellow this scenario is the one i need to cover, the image can be much bigger, but i need it aligned to the left edge of the canvas and also to the right edge.

enter image description here enter image description here

myoda999
  • 335
  • 2
  • 11
  • You need to draw a diagram of what you want to happen. It's not clear at all from your question. It sounds like you want "constrain" which is covered here: https://stackoverflow.com/questions/29399093/using-drawimage-to-output-fixed-size-images-on-a-canvas – gman Oct 30 '19 at 15:47
  • Your diagram is ambigous. what's the image and what's the canvas? From the diagram it looks like you want the size the image vertically to fill the canvas and then be able to choose to align either to the left or the right. The image may or may not get clipped and may or maybe no touch the opposite edge. Is that correct? Your quesiton starts with "I need to center the image" and then you go on to not center tha image. Can you clarify? – gman Oct 30 '19 at 16:33

1 Answers1

0

If I understand correctly here is a schema of your situation:

 leftImageResized
|------------------|


       canvas
       |----|


 => left margin
|------|

If this representation is correct, the width of your left margin equals (width image - width canvas) / 2

And thus replacing

((this.thumbnailWidth/2)-this.leftImageResized.width)/2

by

-(this.leftImageResized.width - this.thumbnailWidth)/2

Should solve it

Sami
  • 648
  • 8
  • 25