1

对不起,如果这属于数学论坛。我在 HTML5s 画布元素中有一个图像圆角,我想让圆角透明。我有以下代码:

    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 是否落在角落应该在的位置之外。有人可以帮忙吗?

4

2 回答 2

1

如果半径是,那么据我从您的代码中可以看出,r左上角圆角是圆弧的圆心位于。(xc1, yc1) = (r, r)您可以类似地计算出其他三个圆心的(xc2, yc2)坐标(xc3, yc3)(xc4, yc4)

然后在第一个角附近,你可以测试 if(x-xc1)*(x-xc1) + (y-yc1)*(y-yc1) > r*rx < xc1y < yc1。这由圆外和相关角内的点来满足。在其他角落,您需要将第一次测试中的圆心更改为相关的圆心,并适当更改其他两个不等式以选择正确的圆象限。

这就是基本的数学。您可以对速度进行许多优化,例如四个角都是对称的(每个角都具有关于对角线的反射对称,并且所有角都是彼此的旋转副本),并且一旦您发现圈外的一个点,您可以立即识别出许多其他点,这些点也在圈外,而无需直接测试它们。

于 2012-04-09T15:12:13.920 回答
1

对于 HTML5 画布,您应该使用所需的不透明度绘制图像,然后使用 将destination-in globalCompositeOperation其贴在图像上,而不是使用像素数据手动设置不透明度。既容易又快得多。

(或者预先填充您想要的区域,然后source-in在将图像绘制到该区域时使用合成模式。)

或者,使用您想要的形状创建一个路径,并使用它clip()来强制您的 drawImage 适合路径

于 2012-04-09T15:16:22.517 回答