是否可以使用图像而不是颜色“填充”HTML5画布上的形状?
我画了一堆形状(四角形以45度角切片)。我想能够用图像“填充”这些形状,而不是颜色。现在我有一句话说:
- context.fillStyle = '#123456' // example fill color
我正在寻找的是像:
- context.fillStyle = 'url(http://www.myimagereference.com/image.png)';
我知道我不能以这种方式使用fillStyle – 但是有另一种方式来实现这种事情吗?
解决方法
您可以通过定义与您的形状相同的
clipping region,然后使用drawImage()绘制到此区域来执行此操作;然后中风(只)你的路径在此之上。
我在我的网站上为你创建了一个这样的技术的例子:
http://phrogz.net/tmp/canvas_image_as_background_to_shape.html
以下是相关代码;它按比例缩放图像以填充您指定的宽度:
- function clippedBackgroundImage( ctx,img,w,h ){
- ctx.save(); // Save the context before clipping
- ctx.clip(); // Clip to whatever path is on the context
- var imgHeight = w / img.width * img.height;
- if (imgHeight < h){
- ctx.fillStyle = '#000';
- ctx.fill();
- }
- ctx.drawImage(img,imgHeight);
- ctx.restore(); // Get rid of the clipping region
- }
如果你想要平铺,不对称拉伸,低透明度着色等等,你可以修改它。这是你可以如何使用它:
- function slashedRectWithBG( ctx,x,y,h,slash,img ){
- ctx.save(); // Save the context before we muck up its properties
- ctx.translate(x,y);
- ctx.beginPath();
- ctx.moveTo( slash,0 ); ////////////
- ctx.lineTo( w,0 ); // //
- ctx.lineTo( w,h-slash ); // //
- ctx.lineTo( w-slash,h ); // //
- ctx.lineTo( 0,h ); // //
- ctx.lineTo( 0,slash ); ////////////
- ctx.closePath();
- clippedBackgroundImage( ctx,h );
- ctx.stroke(); // Now draw our path
- ctx.restore(); // Put the canvas back how it was before we started
- }
请注意,当您创建图像传递给该功能时,您必须要set its onload
handler before setting the src
:
- var img = new Image;
- img.onload = function(){
- // Now you can pass the `img` object to varIoUs functions
- };
- img.src = "...";