dabadaba
dabadaba

Reputation: 9512

How to apply an image as the color for a text made with canvas

Here's a generic text 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);

How can I create that text with an image as its strokeStyle and fillStyle instead of black or whatever color?

Upvotes: 1

Views: 101

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206008

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

Upvotes: 1

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

There is an example at MDN - Applying styles and colors. Applied to your text

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);
}

See full JSFiddle

Upvotes: 1

user1693593
user1693593

Reputation:

After filling the text on canvas, change composite mode:

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

Then draw the image over the text and the text only will be replaced with the image.

Upvotes: 1

Related Questions