JS畫線,雖然很原始,但是兼容所有瀏覽器

用Javascript畫線的方法很多,有SVG,VML、canvas等,但是在現階段,貌似這些方法都不能兼容所有瀏覽器。所以我還是用最原始的辦法法寫瞭一個畫線方法。思路也很簡單,就是用一個像素的DIV拼成一條線。
Js代碼 
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(p); 
    node.className = line; 
    node.style.marginTop = y; 
    node.style.marginLeft = x; 
    container.appendChild(node); 

 
當然還需要一段CSS來控制樣式:
Css代碼 
p.line { 
    position:absolute; 
    z-index:2; 
    width:1px; 
    height:1px; 
    font-size:1px; 
    background-color:#0000FF; 
    overflow:hidden; 

 
來一段HTML測試一下
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> 
    <p id=”container” style=”width:400px;height:400px;border:1px solid #000000;margin-left:50px”></p> 
    <input type=”button” value=”line” onclick=”testLine();”></input> 
</body> 
</html> 

You May Also Like