[英]How to apply an image as the color for a text made with canvas
這是一個通用文本畫布:
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var x = 85;
var y = 65;
context.font = '40pt Calibri';
context.lineWidth = 3;
context.strokeStyle = 'black';
context.strokeText('This is my text', x, y);
context.fillStyle = 'black';
context.fillText('This is my text', x, y);
如何創建帶有圖像的文本作為strokeStyle
和fillStyle
而不是黑色或任何顏色?
在畫布上填充文本后,更改復合模式:
context.globalCompositeOperation = 'source-in'; /// or source-atop
然后在文本上繪制圖像,文本將僅替換為圖像。
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
cw = canvas.width,
ch = canvas.height,
x = 85,
y = 65,
img = new Image();
function txt2img() {
context.font = '40pt Calibri';
context.fillText('This is my text', x, y);
context.globalCompositeOperation = "source-in";
context.drawImage(img, 0, 0, img.width, img.height, 0, 0, cw, ch);
}
img.onload = txt2img;
img.src = "image.jpg";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.