2015-05-19 54 views
0

裏面我有以下的畫布圖像:多邊形添加HTMLImageElement現有畫布

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

回答

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>