Search code examples
javascripthtmlcanvasdrawing

Determine bounds of shape / graphics drawn into a Canvas


I have a simple HTML5 Canvas example that lets the user draw paths onto a canvas. Is there any way to determine the rectangular bounds of the path / shape that was drawn? (i.e., what is the width, height of the rectangular region surrounding the path).

I realize I could do the math while the shape is being drawn to figure out the bounds, but I wanted to see if there was an easier / built in way.


Solution

  • I assume you are using lineTos the only way I could think of would be to keep a min/max stored for the height and width as the user is drawing paths. Other than that the only way to pull back info from the canvas would be to use getImageData which will only give you raw pixel information.

    Quick example showing this

    var ctx = document.getElementById("canvas").getContext("2d");
    var xMin, xMax, yMin, yMax;
    
    // These are set to where the path starts, i start them at 10,10
    xMin = xMax = 10;
    yMin = yMax = 10;
    
    ctx.beginPath();
    ctx.moveTo(10,10);
    
    for(var i = 0; i <10; i++){
        var x = Math.floor(Math.random()*150),
            y = Math.floor(Math.random()*150);
            
        ctx.lineTo(x,y);
        if(x < xMin){
         xMin = x;   
        }
        if(x > xMax){
         xMax = x;   
        }
        
        if(y < yMin){
         yMin = y;   
        }
        if(y > yMax){
         yMax = y;   
        }
    }
    ctx.strokeStyle = "rgb(0,0,0)";
    ctx.stroke();
    ctx.closePath();      
    
    ctx.strokeStyle = "rgb(255,0,0)";
    ctx.strokeRect(xMin,yMin,xMax - xMin,yMax - yMin);  
    #canvas{
        width: 300px;
        height: 300px;
    }
    <canvas id="canvas"></canvas>

    note I just create a bunch of random points. The main thing to remember is set the min/max vals to the coords of the first path a user creates.

    I guess you knew that though, so the real answer is no there is unfortunately no built in way currently to do it..