图像作为“背景”;到绘制的形状
是否可以使用图像而不是颜色来“填充” HTML5 画布上的形状?
我画了一堆形状(各个角以 45 度角切掉的正方形)。我希望能够用图像而不是颜色来“填充”这些形状。目前我有一行指出:
context.fillStyle = '#123456' // example fill color
我正在寻找的是这样的东西:
context.fillStyle = 'url(http://www.myimagereference.com/image.png)';
我知道我不能以这种方式使用 fillStyle - 但还有其他方法可以实现这种事情吗?
Is it possible to 'fill' a shape on an HTML5 canvas with an image instead of a color?
I've drawn a bunch of shapes (squares with various corners sliced off at 45 degree angles). I'd like to be able to 'fill' these shapes with an image, instead of a color. At the moment I've got a line stating:
context.fillStyle = '#123456' // example fill color
What I'm looking for is something like:
context.fillStyle = 'url(http://www.myimagereference.com/image.png)';
I know that I can't use fillStyle this way - but is there another way to achieve this kind of thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能想看看 createPattern
下面是一个简单的代码,演示了 createPattern 的使用
尝试一个示例
You might wanna have a look at createPattern
below is a simple code which demonstrates the use of createPattern
Try an Example
您可以通过定义 剪切区域与您的形状相同,然后使用
drawImage()
绘制到该区域;然后(仅)在此之上描画您的路径。我在我的网站上为您创建了此技术的示例:
http://phrogz.net/tmp/canvas_image_as_background_to_shape.html
这是相关代码;它会按比例缩放图像以填充您指定的宽度:
如果您想要平铺、不对称拉伸、低不透明度着色等,则由您自行修改。以下是您可以如何使用它:
请注意,当您创建图像时传递给函数,您必须 设置其
设置
src
之前的 onload
处理程序:You can do this by defining a clipping region that is the same as your shape and then using
drawImage()
to draw into this region; then stroke (only) your path on top of this.I've created an example of this technique for you on my website:
http://phrogz.net/tmp/canvas_image_as_background_to_shape.html
Here's the relevant code; it proportionately scales the image to fill the width you specify:
It's up to you to modify that if you want tiling, or asymmetric stretching, low-opacity tinting, etc. Here's how you might use it:
Note that when you create your image to pass to the function, you must set its
onload
handler before setting thesrc
: