0

I have the following canvas image:

enter image description here

I know the coordinates of points marked with green and I need to add image as overlay, but I need to skew the image as well.

I know how to position image on the right place, but I have no idea how to skew it.

var div = document.createElement('div');
div.setAttribute('id', 'mask');
div.style.position = 'absolute';
div.style.left = parseFloat(desc.pt1.x) + 'px';
div.style.top  = parseFloat(desc.pt1.y) + 'px';
div.style.background = 'white';
image.appendChild(div);
Kristian Vitozev
  • 5,791
  • 6
  • 36
  • 56

1 Answers1

2

You can use transform:rotate to rotate an img element over the red rectangle on the canvas.

enter image description here

Here's how to calculate the proper angle:

// given the top-left point and the top-right point on the rectangle
var pt0={x:100,y:100};
var pt1={x:250,y:50};

// calculate the angle of the line connecting pt0 and pt1
var dx=pt1.x-pt0.x;
var dy=pt1.y-pt0.y;
var radianAngle=(Math.atan2(dy,dx)+Math.PI*2)%(Math.PI*2);
var degreeAngle=radianAngle*180/Math.PI;

Here's example code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var wrapper=document.getElementById('wrapper');
var image1=document.getElementById('image1');


var pt0={x:50,y:100};
var pt1={x:200,y:50};

// calculate the angle of the line connecting pt0 and pt1
var dx=pt1.x-pt0.x;
var dy=pt1.y-pt0.y;
var angle=(Math.atan2(dy,dx)+Math.PI*2)%(Math.PI*2);
var degreeAngle=angle*180/Math.PI;

dot(pt0.x,pt0.y);
dot(pt1.x,pt1.y);
ctx.beginPath();
ctx.moveTo(pt0.x,pt0.y);
ctx.lineTo(pt1.x,pt1.y);
ctx.stroke();

var bb=canvas.getBoundingClientRect();
image1.style.top=(pt0.y)+'px';
image1.style.left=(pt0.x)+'px';
image1.style.transformOrigin='left top';
image1.style.transform='rotate('+degreeAngle+'deg)';

function dot(x,y){
  ctx.beginPath();
  ctx.arc(x,y,10,0,Math.PI*2);
  ctx.closePath();
  ctx.fillStyle='gold';
  ctx.fill();
}
body{ background-color: ivory; margin:10px;}
#wrapper{position:relative;}
#canvas{border:1px solid red; position:absolute;}
#image1{border:1px solid red; position:absolute;}
<div id=wrapper>
  <canvas id="canvas" width=300 height=300></canvas>
  <img id=image1 src='https://dl.dropboxusercontent.com/u/139992952/multple/rightarrow.png'>
</div>
markE
  • 102,905
  • 11
  • 164
  • 176