function drawLine(startObj, endObj) {
//startObj传入的开始dom,endObj结束Dom
const y_start = startObj.offsetTop + startObj.offsetHeight / 2;
const x_start = startObj.offsetLeft + startObj.offsetWidth / 2;
const y_end = endObj.offsetTop + endObj.offsetHeight / 2;
const x_end = endObj.offsetLeft + endObj.offsetWidth / 2;
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "100%");
svg.setAttribute("height", "100%");
svg.style.position = "absolute";
svg.style.top = "0";
svg.style.left = "0";
svg.style.zIndex = "1";
const arrow = document.createElementNS("http://www.w3.org/2000/svg", "line");
arrow.setAttribute("x1", x_start);
arrow.setAttribute("y1", y_start);
arrow.setAttribute("x2", x_end);
arrow.setAttribute("y2", y_end);
arrow.setAttribute("stroke", "green");//箭头的颜色
arrow.setAttribute("stroke-width", "2");
arrow.setAttribute("marker-end", "url(#arrowhead)");
const marker = document.createElementNS("http://www.w3.org/2000/svg", "marker");
marker.setAttribute("id", "arrowhead");
marker.setAttribute("markerWidth", "10");
marker.setAttribute("markerHeight", "10");
marker.setAttribute("refX", "8");
marker.setAttribute("refY", "3");
marker.setAttribute("orient", "auto");
marker.setAttribute("markerUnits", "strokeWidth");
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", "M0,0 L0,6 L9,3 z");
path.setAttribute("fill", "green");//线的颜色
marker.appendChild(path);
svg.appendChild(marker);
svg.appendChild(arrow);
return svg;
}
window.onresize = function () {
//获取页面svg进行清除然后再次重新绘制,根据窗口自适应
const svgElements = document.getElementsByTagName('svg');
const svgArray = Array.from(svgElements);
svgArray.forEach(element => {
element.remove();
});
document.body.appendChild(drawLine(start, end));传入开始元素结束元素
};
以上是js部分,监听窗口变化,
.line {
position: absolute;
background: green;
height: 1px;
z-index: 1;
}
以上是cssbufen,利用绝对定位使svg脱离文档流