您可以通过三种方式做到这一点:
方法一——使用图案填充球
定义要用作图案的图像:
/// create a pattern
var pattern = context.createPattern(img, 'repeat');
现在您可以将图案用作填充样式而不是绿色:
context.fillStyle = pattern;
但是,由于图案总是在坐标的 origo(默认 0, 0)处绘制,因此您需要为每个移动进行平移。幸运的是没有那么多额外的代码:
/// to move pattern where the ball is
context.translate(x, y);
context.beginPath();
/// and we can utilize that for the ball as well so we draw at 0,0
context.arc(0, 0, radius, 0, Math.PI * 2);
context.closePath();
context.fillStyle = pattern;
context.fill();
现在,根据您想要的移动方式,您周围的球可能需要也可能不需要每次都平移回来。
Here's an online demo showing this approach.
方法 2 - 使用路径裁剪来裁剪图像以适应球
我们可以使用 drawImage 来代替图案来绘制图像。但是,问题在于这将绘制一个正方形,因此除非您创建一个球形图像,该图像适合您的球顶部且具有透明像素。
因此,您可以使用裁剪来实现与使用模式方法相同的效果:
这里只需要多几行:
/// define the ball (we will use its path for clipping)
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2);
context.closePath();
/// as we need to remove clip we need to save current satte
context.save();
/// uses current Path to clip the canvas
context.clip();
/// draw the ball which now will be clipped
context.drawImage(img, x - radius, y - radius);
/// remove clipping
context.restore();
Here's an online demo of this approach.
方法 3 - 将球预剪辑为图像
在 Photoshop 或一些类似程序中制作一个球,然后将其绘制为图像,而不是绘制然后填充的弧。
您只需绘制球,而不是使用圆弧创建路径:
drawImage(ballImage, x - radius, y -radius);
如果您需要绘制不同尺寸,只需将调用扩展到:
drawImage(ballImage, x - radius, y - radius, radius, radius);
如果性能很关键,这是要走的路,因为它比其他两种方法性能更好,但不如它们灵活。
如果您需要在灵活性和性能之间取得平衡,那么剪辑方法似乎是最佳选择(这可能因浏览器而异,因此请测试一下)。
Here's an online demo with drawImage