简体   繁体   中英

Closer Look at HTML5 Canvas fillStyle

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?

Instead of arc's xy 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM