我按transform: rotate
旋转元素,然后将offset(top:XXX, left:YYY)
设置为此元素。
它在Chrome和FF中完美运行,但Safari只计算偏移而不考虑旋转和显示错误坐标的元素。
function drawLine(a, b, line) {
var pointA = $(a).offset();
var pointB = $(b).offset();
var pointAcenterX = $(a).width() / 2;
var pointAcenterY = $(a).height() / 2;
var pointBcenterX = $(b).width() / 2;
var pointBcenterY = $(b).height() / 2;
var angle = Math.atan2(pointB.top - pointA.top, pointB.left - pointA.left) * 180 / Math.PI;
var distance = lineDistance(pointA.left, pointA.top, pointB.left, pointB.top);
distance = ((distance / image.w) * 100).toFixed(2);
$(line).css('transform', 'rotate(' + angle + 'deg)');
$(line).css('width', distance + '%');
if(pointB.left < pointA.left) {
if(pointB.top < pointA.top) {
$(line).offset({top: pointB.top + pointBcenterY, left: pointB.left + pointBcenterX});
} else {
$(line).offset({top: pointA.top + pointBcenterY, left: pointB.left + pointBcenterX});
console.log(pointA.top + pointBcenterY, pointB.left + pointBcenterX);
}
} else {
if(pointB.top < pointA.top) {
$(line).offset({top: pointB.top + pointAcenterY, left: pointA.left + pointAcenterX});
} else {
$(line).offset({top: pointA.top + pointAcenterY, left: pointA.left + pointAcenterX});
}
}
}