您可以通过定义与您的形状相同的
clipping region,然后使用drawImage()绘制到此区域来执行此操作;然后中风(只)你的路径在此之上。
以下是相关代码;它按比例缩放图像以填充您指定的宽度:
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,0,0,w,imgHeight);
ctx.restore(); // Get rid of the clipping region
}
如果你想要平铺,不对称拉伸,低透明度着色等等,你可以修改它。这是你可以如何使用它:
function slashedRectWithBG( ctx, x, y, w, 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, img, w, h );
ctx.stroke(); // Now draw our path
ctx.restore(); // Put the canvas back how it was before we started
}
var img = new Image;
img.onload = function(){
// Now you can pass the `img` object to various functions
};
img.src = "...";