Fill the gap between two points with <div>

Today I conducted an experiment to find out what I can do with <div>s. So I made a simple Paint-like program that 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 the points. So I created a function called fillDotthat draws 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 only works fine when I draw horizontal lines. When I draw from top to bottom or from bottom to top, there will still be spaces. I found something called the Bresenham line algorithm that can do the same, but I don't know how to use it ...

, ?

ps: , <canvas>, , <div>.

+5
1

Nevermind, Bresenham JavaScript, !

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;
     }
   }
}
+1

All Articles