Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill gap between 2 point with <div>

I did an experiment today to see what I can do with <div>s. So I made a simple Paint-like program, which you can draw with <div>s.

$(window).mousemove(function(e){
    if(!mousedown){
        return false;
    }
    var x = e.clientX,
        y = e.clientY;

    drawDot(x,y,ele);

    lastX = x;
    lastY = y;          
});

This is part of the code. It works, but there are gaps between dots. So I created a function called fillDot which will draw a line from point A (last point) to point B (current point).

drawDot(x,y,ele);

fillDot(lastX,lastY,x,y,ele);
function fillDot(lx,ly,x,y,canvas){
    var rise = y - ly,
        run = x - lx,
        slope = rise / run,
        yInt = y - (slope * x);
    if( lx < x ){
        for(var i = lx; i < x ; i+=.5){
            var y = slope * i + yInt;
            drawDot(i,y,canvas);
        }
    }else if( x < lx ){
        for(var i = x; i < lx ; i++){
            var y = slope * i + yInt;
            drawDot(i,y,canvas);
        }
    }
}

It works fine only when I am drawing horizontal-ish lines. When I draw from top to bottom or bottom to top, there will still be gaps. I found something called Bresenham's line algorithm which can do the same thing, but I don't know how to use it...

Any idea how to fill all points in between?

ps: I know there is <canvas>, but I am testing what I can do with <div>.

like image 675
Derek 朕會功夫 Avatar asked Nov 13 '22 01:11

Derek 朕會功夫


1 Answers

Nevermind, I translated the Bresenham's line algorithm into JavaScript and it works perfectly now!

function fillDot(x0, y0, x1, y1){
   var dx = Math.abs(x1-x0);
   var dy = Math.abs(y1-y0);
   var sx = (x0 < x1) ? 1 : -1;
   var sy = (y0 < y1) ? 1 : -1;
   var err = dx-dy;

   while(true){

     drawDot(x0,y0);

     if ((x0==x1) && (y0==y1)) break;
     var e2 = 2*err;
     if (e2>-dy){
       err -= dy;
       x0  += sx;
     }
     if (e2 < dx){
       err += dx;
       y0  += sy;
     }
   }
}
like image 90
Derek 朕會功夫 Avatar answered Dec 22 '22 09:12

Derek 朕會功夫