节点画布库:文本不可见且位于图像下方

问题描述 投票:0回答:1

我正在尝试使用 node-canvas npm 包从画布生成图像。 但文本(标题 1 和标题 2)出现在图像下方。我希望图像成为跨越画布大小的背景,然后将文本放在图像上。

这是我的代码:

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

// Dimensions for the image/canvas
const width = 848;
const height = 600;

// Instantiate the canvas object
const canvas = createCanvas(width, height);
const context = canvas.getContext("2d");

context.font = "bold 70pt 'PT Sans'";
context.textAlign = "center";
context.fillStyle = "#764abc";

context.fillText("TITLE 1", 600, 170);

context.font = "bold 100pt 'PT Sans'";
context.textAlign = "center";
context.fillStyle = "#764abc";

context.fillText("TITLE 2", 600, 270);

// Write the image to file
loadImage("./assets/jimp-cert-template.jpg").then((image) => {
  const pattern = context.createPattern(image, "no-repeat");
  context.fillStyle = pattern;
  context.fillRect(0, 0, width, height);
  const buffer = canvas.toBuffer("image/jpeg");
  fs.writeFileSync("./image.jpeg", buffer);
});

我尝试在画布中绘制文本之前放置 loadImage 函数,但这也不起作用。我希望图像成为跨越画布大小的背景,然后将文本放在图像上。

javascript html node.js canvas node-canvas
1个回答
0
投票

我尝试添加一些日志,发现问题是在上下文中绘制文本后,图像在上下文中设置。因此,由于图像是在最后的上下文中设置的,因此图像会覆盖文本。

这是工作代码:

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

// Dimensions for the image
const width = 848;
const height = 600;

// Instantiate the canvas object
const canvas = createCanvas(width, height);
const context = canvas.getContext("2d");

loadImage("./assets/jimp-cert-template.jpg").then((image) => {
  console.log("Drawing background Image");
  const pattern = context.createPattern(image, "no-repeat");
  context.fillStyle = pattern;
  context.fillRect(0, 0, width, height);
  context.font = "bold 70pt 'PT Sans'";
  context.textAlign = "center";
  context.fillStyle = "#764abc";

  console.log("Writing title1");
  context.fillText("TITLE 1", 600, 170);

  context.font = "bold 100pt 'PT Sans'";
  context.textAlign = "center";
  context.fillStyle = "#764abc";
  console.log("Writing title2");
  context.fillText("TITLE 2", 600, 270);
  const buffer = canvas.toBuffer("image/jpeg");
  fs.writeFileSync("./image.jpeg", buffer);
  console.log("Generated Certificate!!");
});

// Write the image to file
© www.soinside.com 2019 - 2024. All rights reserved.