Roman
Roman

Reputation: 4513

How to compute transform in HTML Canvas by coordinates

I've got a canvas in HTML with an image I load. The image has size (width, height). I get 2 coordinates - (x1, y1) and (x2, y2) - those are the the left-top and right-top corners of the target transform.

What I need to do is to take the original image, put its left-top corner in (x1, y1) and transform it so that the right-top will be in (x2,y2) - which I guess needs a skew transform.

The question would be how to calculate the right skew to put the right-top corner exactly in (x2,y2). Putting the left-top corner in (x1,y1) requires a simple translate transform - no problem there.

Many thanks,

Please see attached image:

enter image description here

Upvotes: 0

Views: 429

Answers (2)

GameAlchemist
GameAlchemist

Reputation: 19294

You have to use setTransform to be able to skew your image.

ctx.setTransform ( scaleX, skewX, skewY, scaleY, transX, transY ) ;

You want to change skewX, so that when x is == to the width, y is changed by targetSkew, so :

skewX =  targetSkew / width 

http://jsbin.com/kivoraqa/1/edit?js,output

function fillRectSkewed(x,y,w,h,sk) {
  ctx.save();
   var skewRatio=sk/w;
   ctx.setTransform(1,skewRatio,0,1, x,y);
   ctx.fillRect(0, 0, w,h);
  ctx.restore();
  }

fillRectSkewed(40,40, 80,40, 20);

enter image description here

In your case, call fillRectSkewed(x1, y2, imageWidth, imageHeight, y1-y2 );

Upvotes: 1

user3806624
user3806624

Reputation: 3

you can use the MSpaint for getting the coordinates of the (X,Y) or you can use this website for easier referencing Image mapping generator

Upvotes: 0

Related Questions