javascript - 在现有 Canvas 内的多边形中添加 HTMLImageElement

标签 javascript html canvas

我有以下 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);

最佳答案

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

enter image description here

以下是计算正确 Angular 方法:

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

关于javascript - 在现有 Canvas 内的多边形中添加 HTMLImageElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30333272/

相关文章:

javascript - 不能在 React Native 中只调用一次函数?

javascript - 悬停几秒后启动功能

javascript - 如何更改数据表插件中按钮的默认名称?

html5 - 拖动 Canvas

canvas - 折纸类折纸动画推荐的 JS 库

JavaScript:如何从 Array.reduce() 函数返回映射数组?

javascript - 为什么 jQuery 或诸如 getElementById 之类的 DOM 方法找不到元素?

javascript - <tr> onclick 有效,但我也想要视觉效果

javascript - 将输入中的值转换或提取为纯文本

javascript - react js : how to draw svg into a canvas that doesn't exist yet?