在html页面上绘制线条 [英] Drawing lines on html page
本文介绍了在html页面上绘制线条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们如何在html页面中绘制一条线。我尝试使用画布,但发现它不工作。也许浏览器不支持它。还可以有其他更简单的方法。
编辑:也许它有点晚,但这里是我的新实现。希望它更易读。 函数createLineElement(x,y,length,angle){
var line = document。的createElement( DIV);
var styles ='border:1px纯黑色; '
+'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); '
+'位置:绝对; '
+'top:'+ y +'px;' '
+'left:'+ x +'px;' ;
line.setAttribute('style',styles);
返回线;
函数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));
解释(如他们所说的一张图片胜过千言万语):
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.
解决方案
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"):
这篇关于在html页面上绘制线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文