[英]Using image mask with globalCompositeOperation on KonvaJS?
[英]Using globalCompositeOperation to mask canvas text with an image; how do i mask the text only but not its stroke?
我想在畫布文本周圍使用白色邊框/描邊,但是我也希望文本具有遮罩(而不是邊框)。 這可能嗎?
這是我當前正在使用的代碼:
function wrapText(ctx, text, x, y, maxWidth, lineHeight) {
var cars = text.split("\n");
for (var ii = 0; ii < cars.length; ii++) {
var line = "";
var words = cars[ii].split(" ");
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + " ";
var metrics = ctx.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth) {
ctx.fillText(line, x, y);
line = words[n] + " ";
y += lineHeight;
}
else {
line = testLine;
}
}
ctx.fillText(line, x, y);
y += lineHeight;
}
}
function draw(x) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.beginPath();
// put text on canvas
var maxWidth = canvas.width - 100;
var lineHeight = 100;
var x = (canvas.width - maxWidth) / 2;
var y = 100;
ctx.font = "50px crewniverse_font";
ctx.strokeStyle = 'white';
ctx.miterLimit = 2;
ctx.lineJoin = 'circle';
ctx.lineWidth = 7;
ctx.strokeText(inputText.value, x, y);
ctx.lineWidth = 1;
wrapText(ctx, inputText.value, x, y, maxWidth, lineHeight); //wrap the text
// draw the mask
ctx.beginPath();
ctx.globalCompositeOperation = "source-in";
ctx.drawImage(img, y * 4, y * 4, img.width, img.height, 0, 0, canvas.width, canvas.height);
ctx.restore();
}
function init() {
canvas.width = canvas.height = 1000;
submitButton = document.getElementById('submit-button');
submitButton.addEventListener('click', function() {
draw();
});
}
如果我刪除wrapText()函數並僅使用ctx.fillText(inputText.value,canvas.width / 2,20,canvas.width)添加文本,這就是我得到的。 代替。
任何想法如何做到這一點?
完成合成后,只需繪制筆觸。
簡化代碼:
var img = new Image(); img.onload = draw; img.src = "https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg" var ctx = c.getContext('2d'); function draw() { // first fill the text ctx.font = '60px Impact'; ctx.fillText('Hello World', 20, 80); // then do the compositing ctx.globalCompositeOperation = "source-in"; ctx.drawImage(this, 0, 0); // finally go back to normal gCO ctx.globalCompositeOperation = "source-over"; // and stroke the text ctx.strokeStyle = 'green'; ctx.lineWidth = 2; ctx.strokeText('Hello World', 20, 80); }
<canvas id="c"></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.