在现有画布

时间:2015-05-19 18:22:37

标签: javascript html canvas

我有以下画布图片:

enter image description here

我知道用绿色标记的点的坐标,我需要将图像添加为叠加,但我也需要将图像倾斜。

我知道如何将图像放在正确的位置,但我不知道如何扭曲它。

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);

1 个答案:

答案 0 :(得分:2)

您可以使用transform:rotate在画布上的红色矩形上旋转img元素。

enter image description here

以下是如何计算合适的角度:

// 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;

以下是示例代码和演示:



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>
&#13;
&#13;
&#13;