前端界面基于百分比定位绘制线段的方法
this.drawLine(document.getElementsByClassName('box-item')[0],[
{left: '20%', top: '60%'},
{left: '49%', top: '12%'},
{left: '53%', top: '12%'}
])
// box 要插入线的元素
// data为画线数据 为对象数组 每个对象包含left top 属性
drawLine(box, data) {
// 对象数组长度至少为2 大于2时连续绘制
if (data.length <2 ) {
return
}
let boxW = box.clientWidth
let boxH = box.clientHeight
for(let i=1; i<data.length; i++) {
var start = data[i-1]
var end = data[i]
var div = document.createElement('div')
// let x1 =
div.style.width = this.getLength(start, end, boxW, boxH)
div.style.transform = `rotate(${this.getAngle(start, end, boxW, boxH)}deg)`
div.style.height = '1px'
div.style.position = 'absolute'
div.style.background = 'red'
div.style.transformOrigin = "0% 50%";
div.style.top = start.top
div.style.left = start.left
box.appendChild(div)
}
},
// 计算线的长度
getLength(data1, data2, w, h) {
let x1 = parseFloat(data1.left)
let y1 = parseFloat(data1.top)
let x2 = parseFloat(data2.left)
let y2 = parseFloat(data2.top)
let x = Math.abs(x1 - x2) * w
let y = Math.abs(y1 - y2) * h
let res = (Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))) / w
return res + '%'
},
// 计算线的角度
getAngle(data1, data2, w, h) {
let x1 = parseFloat(data1.left)
let y1 = parseFloat(data1.top)
let x2 = parseFloat(data2.left)
let y2 = parseFloat(data2.top)
let x = (x2 - x1)/h
let y = (y2 - y1)/w
if(x2<x1) {
return (Math.atan(y/x)*180)/Math.PI + 180
} else if (x2===x1) {
return y2 > y1 ? 90 : -90
} else {
return (Math.atan(y/x)*180)/Math.PI
}
},