簡體   English   中英

如何將圖像應用為使用畫布制作的文本的顏色

[英]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);

如何創建帶有圖像的文本作為strokeStylefillStyle而不是黑色或任何顏色?

在畫布上填充文本后,更改復合模式:

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

MDN有一個例子- 應用樣式和顏色 適用於您的文字

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM