I'm trying to draw a line from one point to another. This seems to work ok on 45 degree angles other than the distance is still wrong. But if the angle is not 45 degrees it goes wack.
You click somewhere in the box as first point then somewhere else as second point.Code:<html> <head> <script type="text/javascript"> var paint = { draw : function(point_oneX, point_oneY, point_twoX, point_twoY) { if(point_twoX > point_oneX) point_lengthX = point_twoX - point_oneX else { point_lengthX = point_oneX - point_twoX; point_oneX = point_twoX; } if(point_twoY > point_oneY) point_lengthY = point_twoY - point_oneY else { point_lengthY = point_oneY - point_twoY; point_oneY = point_twoY; } var angle_b = Math.atan(point_lengthX / point_lengthY) * 180 / 3.1415926535897932384626433832795; var angle_a = 90 - angle_b; var point_dist = Math.sqrt((point_lengthX * point_lengthX) + (point_lengthY * point_lengthY)); var current_dist = 0; for(var i=0;i<point_dist;i++) { this.make_pixel((Math.sin(angle_b) * current_dist) + point_oneX, (Math.sin(angle_a) * current_dist) + point_oneY); current_dist += 1; } }, make_pixel : function(x, y) { var ele = document.createElement('<div>'); ele.setAttribute('id', 'p_'+this.pix_count); ele.setAttribute('style', 'background: #FF0000;position:absolute;left:'+x+'px;top:'+y+'px;width:3px;height:3px;'); document.body.appendChild(ele); } }; var x1 = 0; var x2 = 0; var y1 = 0; var y2 = 0; function addpoint(evt) { if(x1 == 0) x1 = evt.clientX; else x2 = evt.clientX; if(y1 == 0) y1 = evt.clientY; else { y2 = evt.clientY; paint.draw(x1,y1, x2,y2); } } //window.onload = function(){paint.draw(50,50, 100,100)}; </script> <style type="text/css"> .image { border: 1px solid #000000; width: 200px; height: 200px; } </style> </head> <body> <div class="image" onclick="addpoint(event)"> </div> </body> </html>
I'm guessing the math isn't quite right. Any help please?
Thanks.




Reply With Quote