Automattic / Automattic/node-canvas

textBaseline top middle and hanging do not align with javascript canvas api

Open
#2,343 2 comments 0 reactions 0 assignees View on GitHub
Bug Text & Fonts
Dominant language
JavaScript
Stars
10.7k
Forks
1.2k
Avg merge
4d 8h
Merged PRs (30d)
1

Description

## Issue or Feature
The textBaseline property does not produce the expected results. I noticed a misalignment between renders of the JavaScript Canvas api and the node-canvas implementation.

It seems like only the `alphabetic` and `bottom` option align with the JavaScript canvas api whereas `top`, `middle` and `hanging` do not.

Is that an expected behavior? If yes how can I align text from both implementations?

## Steps to Reproduce
I overlayed the JavaScript and node-canvas results of the following scripts. Red text is the expected value using the canvas api and blue text is the results from the node-canvas package.
![canvas](https://github.com/Automattic/node-canvas/assets/39738318/afdaa91e-56ab-4f8e-869f-19299f354a8d)

### Node script
```js
import { createCanvas } from "canvas";
import { writeFileSync } from "fs";

function main() {
const canvas = createCanvas(480, 500);
const ctx = canvas.getContext("2d");

ctx.font = "50px Arial";
ctx.globalAlpha = 0.5;
ctx.fillStyle = "blue";

["top", "hanging", "middle", "alphabetic", "bottom"].forEach((baseline, index) => {
ctx.textBaseline = baseline;
ctx.fillText(baseline, 10, index * 90 + 10);

ctx.beginPath();
ctx.moveTo(0, index * 90 + 10);
ctx.lineTo(480, index * 90 + 10);
ctx.stroke();
});

const buf = canvas.toBuffer("image/png", { compressionLevel: 3 });
writeFileSync("./canvas_node.png", buf);
}

main();
```

### HTML
```html


var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.font = "50px Arial";
ctx.globalAlpha = 0.5;
ctx.fillStyle = "red";

["top", "hanging", "middle", "alphabetic", "bottom"].forEach((baseline, index) => {
ctx.textBaseline = baseline;
ctx.fillText(baseline, 10, index * 90 + 10);

ctx.beginPath();
ctx.moveTo(0, index * 90 + 10);
ctx.lineTo(480, index * 90 + 10);
ctx.stroke();
});

// Get buffer from canvas and convert to png
var buffer = canvas.toDataURL("image/png");
var img = document.createElement("img");
img.src = buffer;
document.body.appendChild(img);

```

## Your Environment
canvas@2.11.2 on Ubuntu 22.04.3 LTS (jammy)
node@v18.12.1

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.