samizdatco / skia-canvas

A GPU-accelerated 2D graphics environment for Node.js
MIT License
1.67k stars 63 forks source link

Unwanted string on position text SVG #125

Open anasrar opened 1 year ago

anasrar commented 1 year ago

When output as SVG outline: false, on object text got unwanted value in position attribute x and y

Script

import { Canvas } from "skia-canvas";

const main = async () => {
  const canvas = new Canvas(300, 300);
  const ctx = canvas.getContext("2d");

  ctx.fillText("First", 100.5, 50.5);
  ctx.fillText("Second", 200, 50);
  ctx.fillText("Third", -1, -2);

  const original = (
    await canvas.toBuffer("svg", {
      outline: false,
    })
  ).toString();

  console.log("ORIGINAL OUTPUT:\n" + original);

  const removeUnwanted = original.replace(
    /font-family="(.*)" x="([-\d.]+), ([-\d.,\s]+)" y="([-\d]+)(.*)"/gm,
    `font-family="$1" x="$2" y="$4"`
  );

  // lost float precision on y
  console.log("REMOVE UNWANTED OUTPUT:\n" + removeUnwanted);
};

main();

Output

ORIGINAL OUTPUT:
<?xml version="1.0" encoding="utf-8" ?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300">
        <text font-size="10" font-family="Noto Sans" x="100.5, 105.69, 108.27, 112.39999, 117.18999, " y="50.809998, ">
                        First
        </text>
        <text font-size="10" font-family="Noto Sans" x="200, 205.48999, 211.12999, 215.92999, 221.97998, 228.15997, " y="50.309998, ">
                        Second
        </text>
        <text font-size="10" font-family="Noto Sans" x="-1, 4.5599976, 10.73999, 13.319992, 17.249985, " y="-1.6900005, ">
                        Third
        </text>
</svg>

REMOVE UNWANTED OUTPUT:
<?xml version="1.0" encoding="utf-8" ?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300">
        <text font-size="10" font-family="Noto Sans" x="100.5" y="50">
                        First
        </text>
        <text font-size="10" font-family="Noto Sans" x="200" y="50">
                        Second
        </text>
        <text font-size="10" font-family="Noto Sans" x="-1" y="-1">
                        Third
        </text>
</svg>

Additional Information