javascripthtmlcanvashtml5-canvas

Fill HTML5 arc with a picture - HTML5 Canvas


I have a HTML5 Canvas (JSFiddle) that looks like: enter image description here

I am creating the balls by the following method:

function createball(x,y,r,color){
    context.beginPath();
    context.arc(x,y,r,0,Math.PI*2,true);
    context.fillStyle = color;
    context.fill();

}

How can I fill the ball with image? I mean a image that might have patters or some natural color?


Solution

  • You could create a pattern and set the ball's fillStyle to that pattern

    enter image description here

    Here's example code and a Demo:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    
    
    var img=new Image();
    img.onload=start;
    img.src="https://i.sstatic.net/g3zd5OIz.jpg";
    function start(){
      var pattern=ctx.createPattern(img,'repeat');
      ctx.beginPath();
      ctx.arc(50,50,15,0,Math.PI*2);
      ctx.closePath();
      ctx.fillStyle=pattern;
      ctx.fill();
      ctx.stroke();
    }
    body{ background-color: ivory; }
    #canvas{border:1px solid red;}
    <h4>Source Image:</h4>
    <img src='https://i.sstatic.net/g3zd5OIz.jpg'>
    <h4>Fill Circle with pattern made from source image</h4>
    <canvas id="canvas" width=100 height=100></canvas>