2012-04-08 68 views
1

對不起,如果這屬於數學論壇。我在HTML5s canvas元素中有一個圖像圓角,我想讓圓角透明。我有以下代碼:檢查點是否超出曲線

var cornersImgData = tempContext.getImageData(0, 0, img.width, img.height); 
    var topLeft = getPixel(cornersImgData, 0, 0); 
    var topRight = getPixel(cornersImgData, cornersImgData.width - 1, 0); 
    var bottomLeft = getPixel(cornersImgData, 0, cornersImgData.height - 1); 
    // Check that the rounded corners have actually been applied (e.g. make sure the user hasn't just clicked the button and then undo) 
    var bottomRight = getPixel(cornersImgData, cornersImgData.width - 1, cornersImgData.height - 1); 
    if (('rgb(' + topLeft[0] + ', ' + topLeft[1] + ', ' + topLeft[2] + ')' == _roundedCornersColour) || 
     ('rgb(' + topRight[0] + ', ' + topRight[1] + ', ' + topRight[2] + ')' == _roundedCornersColour) || 
     ('rgb(' + bottomLeft[0] + ', ' + bottomLeft[1] + ', ' + bottomLeft[2] + ')' == _roundedCornersColour) || 
     ('rgb(' + bottomRight[0] + ', ' + bottomRight[1] + ', ' + bottomRight[2] + ')' == _roundedCornersColour)) 
    { 
     for (var x = 0; x < cornersImgData.width; x++) 
     { 
      for (var y = 0; y < cornersImgData.height; y++) 
      { 
       var colour = getPixel(cornersImgData, x, y); 
       if ('rgb(' + colour[0] + ', ' + colour[1] + ', ' + colour[2] + ')' == _roundedCornersColour) 
       { 
        setPixel(cornersImgData, x, y, colour[0], colour[1], colour[2], 0); 
       } 
      } 
     } 
    } 

這工作,但因爲我更換_roundedCornersColour的每個實例有時我結束了圖像本身內更換了幾個像素。我的高中數學有點生疏,我無法弄清楚確定x和y是否落在拐角處的最佳方式。任何人都可以幫忙嗎?

+0

P.S.我知道角落的半徑 – JoeS 2012-04-08 19:14:45

回答

1

如果半徑r,那麼圓,其中左上圓角都是一個電弧在(xc1, yc1) = (r, r),據我可以從你的代碼告訴的中心。您同樣可以計算出其他三個圓心的座標(xc2, yc2),(xc3, yc3)(xc4, yc4)

然後在第一個角落附近,您可以測試(x-xc1)*(x-xc1) + (y-yc1)*(y-yc1) > r*rx < xc1y < yc1。圓圈外和相關角落的點數都滿足這一點。在其他角落中,您需要將第一個測試中的圓心更改爲相關的圓心,並適當更改其他兩個不等式以選擇圓的正確象限。

這是基本的數學。有很多優化可以適用於速度,例如四個角都是對稱的(每個角都有對角線的反射對稱性,所有角都是旋轉副本),並且一旦找到在圓圈外的一個點上,您可以立即識別出許多其他的點,而無需直接進行測試。

1

對於HTML5 Canvas,不要使用像素數據手動設置不透明度,而應該使用所需的不透明度繪製圖像,然後使用destination-inglobalCompositeOperation將其拍攝到圖像上。既簡單又快得多。

(或預填寫你想要的區域,然後用source-in合成模式,當你畫你的形象吧。)

或者,創建一個你想要的形狀和use clip() to force your drawImage to fit within the path的路徑。