Javascript画线脚本不起作用 [英] Javascript draw line script not working
问题描述
在Firefox和Chrome中进行了测试.在旧的Q/A中在SO上找到脚本.脚本声称有效,但对我不起作用.宁愿使用纯JS来解决此问题,也不愿使用HTML5 canvas来支持较旧的浏览器.
Tested in Firefox and Chrome. Script found on SO in an old Q/A. Script claimed to be working, doesn't work for me. Would rather use pure JS to solve this problem instead of HTML5 canvas to support older browsers.
jsfiddle: http://jsfiddle.net/qnkonmgo/
jsfiddle: http://jsfiddle.net/qnkonmgo/
<html>
<head>
<script>
window.onload = function() {
DrawLine(1,1,100,100);
}
function DrawLine(x1, y1, x2, y2){
if(y1 < y2){
var pom = y1;
y1 = y2;
y2 = pom;
pom = x1;
x1 = x2;
x2 = pom;
}
var a = Math.abs(x1-x2);
var b = Math.abs(y1-y2);
var c;
var sx = (x1+x2)/2 ;
var sy = (y1+y2)/2 ;
var width = Math.sqrt(a*a + b*b ) ;
var x = sx - width/2;
var y = sy;
a = width / 2;
c = Math.abs(sx-x);
b = Math.sqrt(Math.abs(x1-x)*Math.abs(x1-x)+Math.abs(y1-y)*Math.abs(y1-y) );
var cosb = (b*b - a*a - c*c) / (2*a*c);
var rad = Math.acos(cosb);
var deg = (rad*180)/Math.PI
htmlns = "http://www.w3.org/1999/xhtml";
div = document.createElementNS(htmlns, "div");
div.setAttribute('style','border:1px solid black;width:'+width+'px;height:0px;-moz-transform:rotate('+deg+'deg);-webkit-transform:rotate('+deg+'deg);position:absolute;top:'+y+'px;left:'+x+'px;');
}
</script>
</head>
<body>
</body>
</html>
推荐答案
这有效.在此处查看小提琴: http://jsfiddle.net/jvs9hLwf/1/
This works. See the fiddle here: http://jsfiddle.net/jvs9hLwf/1/
(function DrawLine(elementId, x1, y1, x2, y2) {
if (y1 < y2) {
var pom = y1;
y1 = y2;
y2 = pom;
pom = x1;
x1 = x2;
x2 = pom;
}
var a = Math.abs(x1 - x2);
var b = Math.abs(y1 - y2);
var c;
var sx = (x1 + x2) / 2;
var sy = (y1 + y2) / 2;
var width = Math.sqrt(a * a + b * b);
var x = sx - width / 2;
var y = sy;
a = width / 2;
c = Math.abs(sx - x);
b = Math.sqrt(Math.abs(x1 - x) * Math.abs(x1 - x) + Math.abs(y1 - y) * Math.abs(y1 - y));
var cosb = (b * b - a * a - c * c) / (2 * a * c);
var rad = Math.acos(cosb);
var deg = (rad * 180) / Math.PI
div = document.getElementById(elementId);
div.setAttribute('style', 'border:1px solid black;width:' + width + 'px;height:0px;-moz-transform:rotate(' + deg + 'deg);-webkit-transform:rotate(' + deg + 'deg);position:absolute;top:' + y + 'px;left:' + x + 'px;');
})("div", 1, 1, 100, 100);
首先-我没有将其放置在window.onload事件中,而是立即使用所需的参数调用该函数,但保留了该函数的名称,以便可以重复使用.
First - instead of putting it in a window.onload event, I immediately invoke the function with the desired parameters, but kept the function name so that it can be reused.
第二个-我已经添加了一个参数,因此您可以指定调用该函数时要在其中画线的元素ID.
Second - I've added in a parameter so you can specify the element ID that you are trying to draw the line in when you call the function.
这篇关于Javascript画线脚本不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!