JS实现画线(兼容所有浏览器)
用Javascript画线的方法很多,有SVG,VML、canvas等,但是在现阶段,貌似这些方法都不能兼容所有浏览器。所以我还是用最原始的办法法写了一个画线方法。思路也很简单,就是用一个像素的DIV拼成一条线。
function line(startX, startY, endX, endY, container) {
if (startX == endX) {
if (startY > endY) {
var tempY = startY;
startY = endY;
endY = tempY;
}
for (var k = startY; k < endY; k++) {
createPoint(container, startX, k);
}
}
// y = ax + b
var a = (startY - endY) / (startX - endX);女装品牌排行榜
var b = startY - ((startY - endY) / (startX - endX)) * startX;
if (Math.abs(startX - endX) > Math.abs(startY - endY)) {
if (startX > endX) {
var tempX = endX;
endX = startX;
startX = tempX;
}
var left = container.style.left;
var top = container.style.top;
for (var i = startX; i <= endX; i++) {
createPoint(container, i, a * i + b);
}
} else {
if (startY > endY) {
var tempY = startY;
startY = endY;
endY = tempY;
}
for (var j = startY; j <= endY; j++) {
createPoint(container, (j - b) / a, j);
}
}集装箱运费
}
function createPoint(container, x, y) {
var node = document.createElement('div');
node.className = 'line';
node.style.marginTop = y;
node.style.marginLeft = x;
container.appendChild(node);
}
当然还需要一段CSS来控制样式:
div.line {
position:absolute;
z-index:2;
width:1px;
height:1px;
font-size:1px;
background-color:#0000FF;
overflow:hidden;
}
来一段HTML测试一下
<html>
<head>
<script type="text/javascript" src="../js/jsline.js"></script>
<script type="text/javascript">
function testLine() {
line(1, 2, 88, 88, document.getElementById('container'));
}
</script>
</head>
<body>
<div id="container" style="width:400px;height:400px;border:1px solid #000000;margin-left:50px"></div>
<input type="button" value="line" onclick="testLine();"></input>
</body>
</html>