如何在HTML画布上使颜色透明?

时间:2018-04-19 12:44:15

标签: javascript html canvas

我有一个已经有东西绘制的HTMLCanvasElement,我需要让它的区域透明。我不知道该区域的坐标,所以我不能使用路径,但我知道我想要摆脱的颜色。

具体来说,我有一个html元素,其中包含如此建议的文本:https://css-tricks.com/adding-stroke-to-web-text/我在画布元素上绘制它,如下所示:Rendering HTML elements to <canvas>

问题是,我希望在进一步使用之前,使我的文本的白色核心在生成的canvas元素上透明。所以只留下文本的笔画。

为什么我不直接在画布上描边文字?原因是我需要调整字母间距,只有CSS样式可以做到这一点。

代码片段有点难以理解,因为实际上它是通过使用Bridge.Net编译C#而生成的,但是应该让我知道我想要做的事情:

ConstructLabel$1: function (toWrite, font, letterSpacing, labelConstructed) {
            if (toWrite == null || Bridge.referenceEquals(toWrite, "")) {
                return null;
            }
            var canvas = document.createElement("canvas");
            var textElement = document.createElement("div");
            textElement.style.width = "auto";
            textElement.style.position = "absolute";
            textElement.style.whiteSpace = "nowrap";
            textElement.style.letterSpacing = letterSpacing;
            textElement.style.font = font;

            //make the storking of text
            textElement.style.color = "white";
            textElement.style.textShadow = "-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000";

            textElement.textContent = toWrite;

            //ToCanvas is my wrapper that takes a HTML element and returns a new canvas that
            //will draw a 1:1 representation of that element on it. It executes
            //the callback after it being drawn.
            return Utility.ToCanvas(textElement, function (drawnCanvas) {
                var ctx = drawnCanvas.getContext("2d");
                //ctx.ClearColor("white"); <----- how to do this?
                labelConstructed(drawnCanvas);
            });
        }

1 个答案:

答案 0 :(得分:0)

我终于在这里找到了答案:https://gamedev.stackexchange.com/questions/19257/how-do-i-make-magenta-in-my-png-transparent-in-html5-canvas-js在这里应用的是:

ConstructLabel$1: function (toWrite, font, letterSpacing, labelConstructed) {

            [code here as earlier]

            return Utility.ToCanvas(textElement, function (drawnCanvas) {
                var ctx = drawnCanvas.getContext("2d");
                var matrix = ctx.getImageData(0, 0, drawnCanvas.width, drawnCanvas.height);
                var data = matrix.data;
                for (var i = 0; i < data.length; i = (i + 4) | 0) {
                    if (((((data[i] + data[((i + 1) | 0)]) | 0) + data[((i + 2) | 0)]) | 0) === 765) {
                        data[((i + 3) | 0)] = 0;
                    }
                }
                ctx.putImageData(matrix, 0, 0);
                labelConstructed(drawnCanvas);
            });
        },

由于锯齿,这会在文本内侧留下一些大致白色的像素,但如果需要,可以通过更改像素条件来纠正。

像这样进行过滤的结果应该被缓存,因为它是一个长循环来逐个像素地进行过滤。