简体   繁体   English

仔细看看HTML5 Canvas fillStyle

[英]Closer Look at HTML5 Canvas fillStyle

JSFiddle Link (But, please read first) JSFiddle链接(但是,请先阅读)

Let us say, I have a canvas of 400 x 200 让我们说,我有一块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) 我在画布上添加了一个40 x 40的球:(请参见下面的功能)

createdBall(20,20,20)

In this function, the center of the ball is at 20px from top, left and has a radius of 20px. 在此功能中,球的中心距顶部,左侧20px,半径为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. 现在,我再添加一些球: fillStyle搞砸了。

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 : 可以使用transform / translate代替arc的xy,请参见此处

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]. ...之所以有效,是因为... translation(x,y)实际上是将画布的[0,0]原点向右和向下推到[x,y]。 This also pushes the image-pattern from left-top to [x,y] so that it now nicely fits inside the arc. 这也将图像图案从左上角推到[x,y],以使其现在很好地适合弧内。 BTW, it's more efficient to create the pattern once outside the createBall function. 顺便说一句,一旦在createBall函数之外创建模式,效率更高。 ;-) — @markE ;-) — @markE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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