1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 05:47:35 +00:00

LibWeb: Add Canvas Context2D basic text align and text baseline support

Add the CanvasTextDrawingStyles mixin with the textAlign and
textBaseline attributes. Update fill_text in CanvasRenderingContext2D
to move the text rect by the text align and text baseline attributes.
Wrote a simple HTML example to showcase the new features.
This commit is contained in:
Bastiaan van der Plaat 2023-08-03 12:18:17 +02:00 committed by Andreas Kling
parent e689422564
commit 220e34b69d
9 changed files with 159 additions and 9 deletions

View file

@ -0,0 +1,66 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas Text Examples</title>
</head>
<body>
<h1>Canvas Text Examples</h1>
<em>Canvas text-align</em><br>
<canvas id="canvas0" style="border: 1px solid black;"></canvas><br><br>
<script>
(function () {
const canvas = document.getElementById('canvas0');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = 'red';
ctx.beginPath();
ctx.moveTo(canvas.width / 2, 0);
ctx.lineTo(canvas.width / 2, canvas.height);
ctx.stroke();
ctx.font = '16px sans-serif';
ctx.textBaseline = 'top';
const alignments = ['left', 'center', 'right', 'start', 'end'];
let y = 8;
for (const alignment of alignments) {
ctx.textAlign = alignment;
ctx.fillText(`Text align: ${alignment}`, canvas.width / 2, y);
y += 16 + 8;
}
})();
</script>
<em>Canvas text-baseline</em><br>
<canvas id="canvas1" width="1000" style="border: 1px solid black;"></canvas><br><br>
<script>
(function () {
const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = 'red';
ctx.beginPath();
ctx.moveTo(0, canvas.height / 2);
ctx.lineTo(canvas.width, canvas.height / 2);
ctx.stroke();
ctx.font = '12px sans-serif';
ctx.textAlign = 'left';
const baselines = ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'];
let x = 8;
for (const baseline of baselines) {
ctx.textBaseline = baseline;
ctx.fillText(`Baseline: ${baseline}`, x, canvas.height / 2);
x += canvas.width / baselines.length;
}
})();
</script>
</body>
</html>