【发布时间】:2020-06-11 20:18:01
【问题描述】:
我正在尝试使用画布在 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 上创建 textgradient?
【问题讨论】:
-
如果你正在尝试做图像处理,我不推荐使用画布,为什么不试试这个库:npmjs.com/package/jimp。
-
我看过 JIMP,确实它被广泛使用,甚至超过了 Node 环境中的 CANVAS,但对于创建形状或文本操作等常见任务,它比 CANVAS 具有更高的复杂性。但是,我正在寻找解决问题的工具。顺便谢谢。