我畫了一個圓角矩形的網格,我需要填充它們的圖像背景。最終我會有很多圖像背景,但現在,我試圖讓它與其中一個一起工作。我很接近,我的矩形繪製,但填充做一些有點怪異的東西 - 它重疊自己,並殺死我的模式(邊緣除外),基本上填充整個畫布與圖像。我試圖「剪輯」我的路徑,但這隻會導致只填充一個矩形。我不確定我做錯了什麼,我希望畫布專家能夠發現它?爲什麼我的畫布填充圖案自身重複/重疊?
/* 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);
}
}
};
你是如此超越真棒,我不知道該說些什麼,除非是一個非常豐盛的謝意。我很欣賞這個額外的特別迴應,以確定這一點。吃過的beginpath只是跛腳,需要檢查我的眼睛! – littlered 2012-07-13 04:17:07