我使用div来减少宽度来创建线条.我有两个随机点坐标,我想用div画一条线.但是,div只需要一个点坐标及其宽度和高度来创建它们,结果总是一个垂直div.有没有办法旋转div以加入两个随机点?我试过旋转功能,但它使用指定的角度.这是我用于创建div的代码:
function creatediv(id, width, height, left, top, opacity)
{
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.style.width = width + "px";
newdiv.style.height = height + "px";
newdiv.style.position = "absolute";
newdiv.style.left = left + "px";
newdiv.style.top = top + "px";
newdiv.style.background = "red";
newdiv.style.opacity = opacity;
//newdiv.style.transform = "rotate(37deg)";
document.body.appendChild(newdiv);
}
最佳答案 对于两个点•a和•b,两者都具有x y坐标
距离Math.hypot(by-ay,bx-ax)
Degree Math.atan2(by-ay,bx-ax)* 180 / Math.PI;
div比定位顶部,左边根据点坐标.
transformOrigin需要定义为50%,以保持div点为中心:
function creatediv(id, ax,ay, bx,by, size, opacity, color) {
var length = Math.hypot(by-ay, bx-ax),
deg = Math.atan2(by-ay, bx-ax) * 180 / Math.PI;
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.style.width = length + "px";
newdiv.style.height = (size||2) + "px";
newdiv.style.left = ax + "px";
newdiv.style.top = ay + "px";
newdiv.style.background = color || "red";
newdiv.style.opacity = opacity || 1;
newdiv.style.transformOrigin = "left 50%";
newdiv.style.transform = "rotate("+ deg +"deg)";
newdiv.style.position = "absolute";
document.body.appendChild(newdiv);
}
creatediv("a", 20, 20, 200, 80);
几个连接线,以及设置样式的不同方法:
function creatediv(id, ax,ay, bx,by, size, opacity, color) {
var length = Math.hypot(by-ay, bx-ax),
deg = Math.atan2(by-ay, bx-ax) * 180 / Math.PI,
newdiv = document.createElement('div'),
css = {
width: length + "px",
height: (size||2) + "px",
left: ax + "px",
top: ay + "px",
background: color || "red",
opacity: opacity || 1,
transformOrigin: "left 50%",
transform: "rotate("+ deg +"deg)",
position: "absolute"
};
for(var s in css) newdiv.style[s] = css[s];
document.body.appendChild(newdiv);
}
creatediv("a", 0,30, 10,10);
creatediv("b", 10,10, 60,80, 5, 0.3, "#0bf");
creatediv("c", 60,80, 70,50);
creatediv("d", 70,50, 150,90, null, null, "gold");