我画了一个圆角矩形网格,我需要用图像背景填充它们。最终我会有很多图像背景,但现在,我正试图让它与一个一起工作。我很接近,我的矩形绘制但填充有点奇怪 - 它自身重叠并杀死我的图案(边缘除外)基本上用图像填充整个画布。我试图“剪裁”我的路径,但这只会导致填充一个矩形。我不确定我做错了什么,我希望画布专家能发现它?
/* build rounded rectangle */
var roundedRect=function(ctx,x,y,width,height,radius,fill,stroke)
{
ctx.save(); // save the context so we don't mess up others ctx.beginPath();
// draw top and top right corner ctx.moveTo(x+radius,y);
ctx.arcTo(x+width,y,x+width,y+radius,radius);
// draw right side and bottom right corner
ctx.arcTo(x+width,y+height,x+width-radius,y+height,radius);
// draw bottom and bottom left corner
ctx.arcTo(x,y+height,x,y+height-radius,radius);
// draw left and top left corner
ctx.arcTo(x,y,x+radius,y,radius);
ctx.clip();
if(fill){ ctx.fill(); }
if(stroke){ ctx.stroke(); }
ctx.restore(); // restore context to what it was on entry
}
/* onload, fill canvas with pattern of rounded rectangles separated by 2px */
window.onload = function() {
var canvas = document.getElementById("canvas");
/* rounded filled rectangle pattern */
var canvasWidth=530;
var canvasHeight=530;
var recWidth=42;
var recHeight=42;
var grout=2;
var radius=2;
var cols=canvasWidth/(recWidth+grout);
var rows=canvasWidth/(recHeight+grout);
/* loop through each row/column to build pattern */
alert("rows" + rows + " & cols " + cols);
for (i=1; i<rows; i++){
for (j=1; j<cols; j++){
var ctx = canvas.getContext("2d");
/* fill pattern */
var img=document.getElementById("poppy");
var pat=ctx.createPattern(img,"repeat");
ctx.fillStyle=pat;
roundedRect(ctx,(j*grout + (j-1)*recWidth),(i*grout + (i-1)*recHeight),recWidth,recHeight,radius,true,false);
}
}
};