Search code examples
javascripthtml5-canvas

how to fill circle with lines? (canvas ctx 2d)


Is there a way how to fill circle with lines, in same way as it shown in the picture, without math computations for x1y1-x2y2 points on circle body? I mean, something like configuration for gradient or anything else?

enter image description here


Solution

  • Code taken from this mdn article

    Result:

    striped circle

    // Create a pattern, offscreen
    const patternCanvas = document.createElement("canvas");
    const patternContext = patternCanvas.getContext("2d");
    
    // Give the pattern a width and height of 50
    patternCanvas.width = 25;
    patternCanvas.height = 25;
    
    // Give the pattern a background color and draw an arc
    patternContext.fillStyle = "white";
    patternContext.strokeStyle = "green";
    patternContext.lineWidth = 2
    patternContext.fillRect(0, 0, patternCanvas.width, patternCanvas.height);
    patternContext.moveTo(0, 0);
    patternContext.lineTo(25, 25);
    patternContext.stroke();
    
    // Create our primary canvas and fill it with the pattern
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const pattern = ctx.createPattern(patternCanvas, "repeat");
    ctx.fillStyle = pattern;
    ctx.arc(50, 50, 50, 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
    
    // Add our primary canvas to the webpage
    document.body.appendChild(canvas);