Search code examples
htmlgeometryhtml5-canvas

Polygon with a hole in the middle with HTML5's canvas


Using the <canvas> tag I need to be able to draw a hole in a polygon.

Right now I have something very simple that uses beginPath() then does lineTo() for each point. It is then filled with fill().

I cannot see any way to have a filled polygon with a unfilled middle though, like a donut. I'm not making a donut but it is suitable for this example.

Is there something I am missing? I would rather not draw it fully filled then have to redraw the middle.


Solution

  • This is what i made it work:

    var ctx = canvas.getContext("2d");     
    ctx.beginPath();
    
    //polygon1--- usually the outside polygon, must be clockwise
    ctx.moveTo(0, 0);
    ctx.lineTo(200, 0);
    ctx.lineTo(200, 200);
    ctx.lineTo(0, 200);
    ctx.lineTo(0, 0);
    ctx.closePath();
    
    //polygon2 --- usually hole,must be counter-clockwise 
    ctx.moveTo(10, 10);
    ctx.lineTo(10,100);
    ctx.lineTo(100, 100);
    ctx.lineTo(100, 10);
    ctx.lineTo(10, 10);
    ctx.closePath();
    
    //  add as many holes as you want
    ctx.fillStyle = "#FF0000";
    ctx.strokeStyle = "rgba(0.5,0.5,0.5,0.5)";
    ctx.lineWidth = 1;
    ctx.fill();
    ctx.stroke();
    

    The main idea here is you can only use beginPath once; the outside polygon must be clockwise and holes must be counter-clockwise.