Automattic/node-canvas

fillText: \n (and \r\n) splits the text in different lines

Open

#1363 opened on Jan 26, 2019

View on GitHub
 (1 comment) (0 reactions) (0 assignees)JavaScript (9,524 stars) (1,140 forks)batch import
BugHelp wanted

Description

Issue

In browsers, newlines (and carriage return, new line) do not split the rendered text into two lines but render as a space instead, however in canvas, this is not true and splits them. A web developer who has been working with web browsers's canvas would not expect fillText to have multi-line support.

Using the code:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.font = '50px serif';
ctx.textAlign = 'center';
ctx.fillText('Hello world\ntext', 200, 90);

Gets us the same result in Chrome 71.0.3578.98, Edge 44.17763.1.0, and Firefox 64.0.2: image

But canvas (with the adjustments made to use createCanvas()) does multi-line instead: image

The lack of this consistency may confuse some developers (like me) when trying the code in back-end before deploying to front-end, or vice-versa, I am not sure if this was intended or not, as this is not mentioned in any of the non-standard features or variations from the browser canvas.

Steps to Reproduce

const Canvas = require('canvas');

// Create canvas
const canvas = Canvas.createCanvas(400, 150);
const ctx = canvas.getContext('2d');
ctx.font = '50px serif';
ctx.textAlign = 'center';
ctx.fillText('Hello world\ntext', 200, 90);

// write file using `canvas.toBuffer()`

Your Environment

  • Version of node-canvas: 2.2.0
  • Environment: Node.js 10.13.0 on Debian 9

Contributor guide