Javascript 在html页面上画线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4270485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:40:00  来源:igfitidea点击:

Drawing lines on html page

javascripthtml

提问by sam

How can we draw a line in html page. I tried using canvas but found that its not working. Maybe browser doesn't support it. Can there be other easier way.

我们如何在html页面中画一条线。我尝试使用画布,但发现它不起作用。可能浏览器不支持。有没有其他更简单的方法。

回答by madox2

EDIT: Maybe it is little bit late but here is my new implementation. Hope it's more readable.

编辑:也许有点晚了,但这是我的新实现。希望它更具可读性。

function createLineElement(x, y, length, angle) {
    var line = document.createElement("div");
    var styles = 'border: 1px solid black; '
               + 'width: ' + length + 'px; '
               + 'height: 0px; '
               + '-moz-transform: rotate(' + angle + 'rad); '
               + '-webkit-transform: rotate(' + angle + 'rad); '
               + '-o-transform: rotate(' + angle + 'rad); '  
               + '-ms-transform: rotate(' + angle + 'rad); '  
               + 'position: absolute; '
               + 'top: ' + y + 'px; '
               + 'left: ' + x + 'px; ';
    line.setAttribute('style', styles);  
    return line;
}

function createLine(x1, y1, x2, y2) {
    var a = x1 - x2,
        b = y1 - y2,
        c = Math.sqrt(a * a + b * b);

    var sx = (x1 + x2) / 2,
        sy = (y1 + y2) / 2;

    var x = sx - c / 2,
        y = sy;

    var alpha = Math.PI - Math.atan2(-b, a);

    return createLineElement(x, y, c, alpha);
}

document.body.appendChild(createLine(100, 100, 200, 200));

Explanation (as they say "a picture is worth a thousand words"):

解释(正如他们所说的“一张图片值一千字”):

Draw line explanation sketch

画线说明草图

回答by Metagrapher

you could define:

你可以定义:

<div id="line1" class="line vertical"></div>
<div id="line2" class="line horizontal"></div>

.line {
  position: absolute;
  background-color: #000000;
}

.vertical { 
   width: 1px;
   height: 500px;
}

.horizontal {
   width: 500px;
   height: 1px;
}

#line1 {
   top: 20px;
   left: 50%;
}

#line2 {
   top: 260px;
   left: 25%;
}

/* for added rotation effects */
.forty-five {
   transform: rotate(45deg);
}

if you want to get into diagonal lines you could begin to try some rotation withtransform: rotate(45deg);The IE Compatible method of rotating objects is discussed thoroughly here, which is terribly complicated. I do not know the IE compatible way to rotate divs, sorry., but that would work in Safari, Firefox, Chrome, and Opera.

如果你想进入对角线,你可以开始尝试使用transform: rotate(45deg);旋转对象的 IE 兼容方法进行一些旋转here彻底讨论,这是非常复杂的。我不知道旋转 div 的 IE 兼容方式,抱歉。,但这适用于 Safari、Firefox、Chrome 和 Opera。

[EDITS]

[编辑]

2014/11/08- sjc - updated transform rules. Added MozDev links and IE rotation SO links.

2014/11/08- sjc - 更新转换规则。添加了 MozDev 链接和 IE 旋转 SO 链接。

回答by Insomniak Dev

i found myself needing a solution on this so i developped one using "hr" div and some gradient in border-image. Here is a Jsfiddle linkto test it and the code below.

我发现自己需要一个解决方案,所以我使用“hr”div和边框图像中的一些渐变开发了一个解决方案。这是一个用于测试它的Jsfiddle 链接和下面的代码。

<html lang="fr">
<head>
<script>
    window.addEventListener("load",function(){
        function pow2(n){
            return n*n;
        }   

        var p1 = {
            id:"p1",
            x:150,
            y:50
        };
        var p2 = {
            id:"p2",
            x:300,
            y:250
        };
        var select = null;

        function getAngle(){

            var dist = Math.sqrt(pow2(p1.x-p2.x)+pow2(p1.y-p2.y));
            var l = document.getElementById("line");
            var cos = (p2.x-p1.x)/Math.sqrt(pow2(p2.x-p1.x)+pow2(p2.y-p1.y));
            var behind = p1.x < p2.x;
            var higher = p1.y > p2.y;
            l.style.width = (dist*2)+"px";
            l.style.left = (p1.x-dist)+"px";
            l.style.top = (p1.y)+"px";

            l.style.transform = "rotateZ("+(higher?-1:1)*Math.acos(cos)*(180/Math.PI)+"deg)";
        }

        var down = false

        document.addEventListener("mousemove",function(e){
            if(select){
                select.x = e.pageX;
                select.y = e.pageY;
                console.log(p1);
                var p = document.getElementById(select.id);
                p.style.left = (select.x-5)+"px";
                p.style.top = (select.y-5)+"px";
                getAngle();
            }
        });
        document.addEventListener("mouseup",function(e){
            if(!select)
                select = p1;
            else if(select == p1)
                select = p2;
            else 
                select = null;
        });
        document.addEventListener("mousedown",function(e){
            down = true;
        });
    });
</script>
</head>
<body>
<hr id="line" style="
position: absolute;
top: 50px;
left: -100px;
width: 500px;
margin: 0;
-webkit-transform: rotateZ(53.1deg);
border-width: 1px;      border-style: solid;                          
border-image: linear-gradient(to right, #ffffff 0%,#ffffff 49%,#000000 50%,#000000 100%) 1;
"/>
<div id="p1" style="
border-radius: 5px;
width: 10px;
background: #000;
position: absolute;
height: 10px;
top: 45px;
left: 145px;
"></div>
<div id="p2" style="
border-radius: 5px;
width: 10px;
background: #000;
position: absolute;
height: 10px;
top: 245px;
left: 295px;
"></div>
</body>
</html>

hope it helps someone :)

希望它可以帮助某人:)

回答by Vivin Paliath

The <canvas>object isthe easiest way (aside from plopping an image or using flash). Also, please post your code and tell us under what browser you're trying to use <canvas>. We can't tell you what you're doing wrong otherwise.

<canvas>对象(除了plopping图像或使用闪光)的最简单的方法。另外,请发布您的代码并告诉我们您尝试使用的浏览器<canvas>。否则我们无法告诉您您做错了什么。

As far as support is concerned, from Wikipedia:

就支持而言,来自维基百科:

The element is currently supported by the latest versions of Mozilla Firefox, Google Chrome, Safari, and Opera. It is not natively implemented by Internet Explorer (IE) as of version 8[7], though support is in development for Internet Explorer 9; however, many of the Canvas element's features can be supported in IE, for example by using Google or Mozilla plugins, JavaScript libraries and either Adobe Flash or IE's proprietary VML.

目前,最新版本的 Mozilla Firefox、Google Chrome、Safari 和 Opera 支持该元素。从版本 8[7] 开始,它不是由 Internet Explorer (IE) 本地实现的,尽管对 Internet Explorer 9 的支持正在开发中;但是,IE 可以支持 Canvas 元素的许多功能,例如通过使用 Google 或 Mozilla 插件、JavaScript 库以及 Adob​​e Flash 或 IE 的专有 VML。

SVG is another option, but (surprise!) IE doesn't it support it (IE9 is supposed to support some parts of it).

SVG 是另一种选择,但是(令人惊讶!)IE 不支持它(IE9 应该支持它的某些部分)。

I'm also not sure what kind of line you want to draw. I mean, you could just make a divand only enable one of its borders - that would be a straight line.

我也不知道你想画什么样的线。我的意思是,你可以只制作一个div并且只启用它的一个边界——那将是一条直线。

回答by Klemen Slavi?

Not all browsers support the <canvas/>element. Try a cross-browser solution, like FlashCanvasor excanvas.

并非所有浏览器都支持该<canvas/>元素。尝试跨浏览器解决方案,例如FlashCanvasexcanvas

The alternative is using SVG.

另一种方法是使用 SVG。

回答by tim

options for cross browser vector graphics include Rapha?land svgweb

跨浏览器矢量图形选项包括Rapha?lsvgweb

回答by tbem

Hi there i made a jQuery plugin for that propose. It is crossbrowser and don't use SVG or CANVAS. Check it: https://github.com/tbem/jquery.line

嗨,我为该提议制作了一个 jQuery 插件。它是跨浏览器,不使用 SVG 或 CANVAS。检查它:https: //github.com/tbem/jquery.line

回答by Johnny Perth

I find that the < hr > tag works very well if all you want is a horizontal line accross the page.

我发现 < hr > 标签效果很好,如果你只想要一条横穿页面的水平线。

回答by Pete K.

I found this code on w3schools.com at https://www.w3schools.com/tags/canvas_lineto.asp

我在 w3schools.com 的https://www.w3schools.com/tags/canvas_lineto.asp上找到了这个代码

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(300,150);
ctx.stroke();

this allows you to easily draw lines on a canvas. Hope this helps!

这使您可以轻松地在画布上绘制线条。希望这可以帮助!