如何在 canvas nodejs 中创建渐变文本?

how to create gradient text in canvas nodejs?

我正在尝试使用 canvas 在 Node 上创建渐变文本,我测试了下面 https://www.w3schools.com/tags/canvas_filltext.asp 中的代码是一个重新实现,但我收到了一个错误。

const fs = require('fs');
const {
  createCanvas,
  loadImage
} = require('canvas');

const text="Gradient";
const output="./image.png";

async function start(text,output){

let [width,height] = [1280,720];

  const canvas = createCanvas(width, height);

  let context = canvas.getContext("2d");

  await drawGradientText(text);
  await saveImage(output);
  async function drawGradientText(text) {
    return new Promise((resolve) => {

      context.font = "30px Verdana";
      // Create gradient
      let gradient = context.createLinearGradient(0, 0, canvas.width, 0);
      gradient.addColorStop("0", " magenta");
      gradient.addColorStop("0.5", "blue");
      gradient.addColorStop("1.0", "red");
      // Fill with gradient
      context.fillStyle = gradient;
      context.fillText(text, 10, 90);
      resolve();
    })

  }


  function saveImage(output) {
    return new Promise((resolve) => {

      const buffer = canvas.toBuffer('image/png');
      fs.writeFileSync(output, buffer);
      resolve();
    })
  }
}

start(text,output);

控制台显示

TypeError: offset required

(node:18932) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()...

如何在 nodejs 上创建文本渐变?

与浏览器不同,node-canvas 对于作为偏移量传递给 addColorStop( offset, color ) 的类型非常严格。
他们不会将其类型转换为浮动,只会抛出您收到的错误,如 can be seen here..

可以说这是一个互操作问题,他们可能想要修复它,但即使在浏览器中,此偏移量也应该是一个数字,所以传递数字,而不是字符串:

gradient.addColorStop(0, " magenta");

根据凯多的回答https://whosebug.com/users/3702797/kaiido 我注意到必须以十六进制数字格式编写颜色。 代码现在看起来像这样:

const fs = require('fs');
const {
  createCanvas,
  loadImage
} = require('canvas');

const text="Gradient";
const output="./image.png";

async function start(text,output){

let [width,height] = [1280,720];

  const canvas = createCanvas(width, height);

  let context = canvas.getContext("2d");

  await drawGradientText(text);
  await saveImage(output);
  async function drawGradientText(text) {
    return new Promise((resolve) => {

      context.font = "30px Verdana";
      // Create gradient
      let gradient = context.createLinearGradient(0, 0, canvas.width, 0);
            gradient.addColorStop(0, "#004")
      gradient.addColorStop(0.5, "#00fef3")
      context.fillStyle = gradient;
      context.fillText(text, width/2 - , height/2);
      resolve();
    })

  }


  function saveImage(output) {
    return new Promise((resolve) => {

      const buffer = canvas.toBuffer('image/png');
      fs.writeFileSync(output, buffer);
      resolve();
    })
  }
}

start(text,output);