Reputation: 7443
JSFiddle Link (But, please read first)
Let us say, I have a canvas of 400 x 200
<canvas id="myCanvas" width="400" height="200"></canvas>
I added a ball of 40 x 40
to the canvas: (see the function below)
createdBall(20,20,20)
In this function, the center of the ball is at 20px from top, left and has a radius of 20px. (Same Dimensions as original image used)
function createBall(x,y,r){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext("2d");
context.beginPath();
context.arc(x,y,r,0,Math.PI*2,true);
context.fillStyle = context.createPattern(img, 'repeat');
context.fill();
}
The result is:
Now, I add some more balls: The fillStyle is screwed up.
createBall(50,50,20);
createBall(80,80,20);
I found out that what happens that the whole canvas get filled for a second like this and only a part we want to fill is picked. Something like this:
This is what exactly happening with my balls. How do I fill my each Ball with an Image?
Upvotes: 2
Views: 85
Reputation: 21267
Instead of arc's x-y you can use transform/translate, see here:
createBall(20, 20, 20);
createBall(50, 50, 20);
createBall(80, 80, 20);
function createBall(x,y,r){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext("2d");
context.beginPath();
context.translate(x - r, y - r);
context.arc(r, r, r, 0, Math.PI * 2, true);
context.fillStyle = context.createPattern(img, 'repeat');
context.fill();
context.translate(-(x - r), -(y - r));
}
...and this works because... translate(x,y) is actually pushing the canvas's [0,0] origin rightward and downward to [x,y]. This also pushes the image-pattern from left-top to [x,y] so that it now nicely fits inside the arc. BTW, it's more efficient to create the pattern once outside the createBall function. ;-) — @markE
Upvotes: 4