使画布文本蒙版自动居于文本中心

时间:2017-07-20 12:18:53

标签: javascript html5-canvas

我在彼此的顶部有三个不同的画布元素,在中间层我正在绘制带有遮罩图像的文本。

我正在尝试将蒙版图像置于文本的中心位置,因此当我移动文本或更改大小时,蒙版以文本为中心,我不必将其单独设置为居中面具。我不明白我该如何计算它。

My mask looks like this

This is how it looks over the text when ideally centered

When i move the text, the mask doesn't go with it, and i have to align it manually

以下是我的一些代码:

function drawCanvasText(x, y, doStroke) {
    var lines = inputText.value.split("\n");
    var padding;
    (lineSpacing.value == null || lineSpacing.value == "") ? padding = 45 : padding = parseInt(lineSpacing.value);
    //ctx.save();
    //ctx.translate(posX, posY);
    txtctx.fillStyle = "black";
    txtctx.textBaseline = "top";
    for (i = 0; i < lines.length; i++) {
        switch(i) {
            case 0:
                txtctx.font = fontSize1.value + "pt crewniverse_font";
                break;
            case 1:
                var lineHeight = parseInt(fontSize2.value);
                txtctx.font = fontSize2.value + "pt crewniverse_font";
                y = (parseInt(y) + lineHeight) + padding;
                break;
            case 2:
                var lineHeight = parseInt(fontSize3.value);
                txtctx.font = fontSize3.value + "pt crewniverse_font";
                y = (parseInt(y) + lineHeight) + padding + 10;
                break;
        }
        if(doStroke) txtctx.strokeText(lines[i], x, y);
        else txtctx.fillText(lines[i], x, y);
    }
}

function updateCanvasText() {
    var x = inputX.value;
    var y = inputY.value;
    var mask_X = maskX.value;
    var mask_Y = maskY.value;
    txtctx.clearRect(0, 0, txtcanvas.width, txtcanvas.height);
    txtctx.save();
    drawCanvasText(x, y, false);
    txtctx.globalCompositeOperation = "source-in";
    txtctx.drawImage(mask, mask_X, mask_Y, 1200, mask.height, 0, 0, bgcanvas.width, bgcanvas.height);
    txtctx.globalCompositeOperation = "destination-over";
    txtctx.strokeStyle = 'white';
    txtctx.lineWidth = strokeWidth.value;
    txtctx.lineJoin = 'round';
    drawCanvasText(x, y, true);
    txtctx.shadowColor = "#d5efed";
    txtctx.shadowOffsetX = 0;
    txtctx.shadowOffsetY = shadowOffset.value;
    txtctx.shadowBlur = 0;
    drawCanvasText(x, y, true);
    txtctx.restore();
}

(MaskX / Y和inputX / Y是输入字段。)

0 个答案:

没有答案