如何将图像应用为使用画布制作的文本的颜色

时间:2014-01-15 23:12:54

标签: javascript html5 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);

如何使用图片strokeStylefillStyle而不是黑色或任何颜色创建该文字?

3 个答案:

答案 0 :(得分:1)

在画布上填写文本后,更改复合模式:

context.globalCompositeOperation = 'source-in';  /// or source-atop

然后在文本上绘制图像,文本将仅替换为图像。

答案 1 :(得分:1)

LIVE DEMO

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";

答案 2 :(得分:1)

MDN - Applying styles and colors有一个例子。适用于您的文字

var img = new Image();
img.src = 'http://lorempixel.com/100/100';
img.onload = function () {
    // create pattern
    var ptrn = context.createPattern(img, 'repeat');
    context.fillStyle = ptrn;
    context.fillText('This is my text', x, y);
}

查看完整的JSFiddle