Skip to content

Commit

Permalink
toPathData() rounds numbers to three decimal places.
Browse files Browse the repository at this point in the history
  • Loading branch information
fdb committed Mar 13, 2018
1 parent c909021 commit 1310a5b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
17 changes: 11 additions & 6 deletions src/libraries/vg/objects/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ var CLOSE_COMMAND = Object.freeze({ type: CLOSE });

var KAPPA = 0.5522847498307936; // (-1 + Math.sqrt(2)) / 3 * 4

function _roundCoord(n) {
if (n % 1 === 0) return n;
return n.toFixed(3);
}

function _cloneCommand(cmd) {
var newCmd = {type: cmd.type};
if (newCmd.type !== CLOSE) {
Expand Down Expand Up @@ -445,16 +450,16 @@ Path.prototype.toPathData = function () {
for (i = 0; i < this.commands.length; i += 1) {
cmd = this.commands[i];
if (cmd.x !== undefined) {
x = math.clamp(cmd.x, -9999, 9999);
y = math.clamp(cmd.y, -9999, 9999);
x = _roundCoord(math.clamp(cmd.x, -9999, 9999));
y = _roundCoord(math.clamp(cmd.y, -9999, 9999));
}
if (cmd.x1 !== undefined) {
x1 = math.clamp(cmd.x1, -9999, 9999);
y1 = math.clamp(cmd.y1, -9999, 9999);
x1 = _roundCoord(math.clamp(cmd.x1, -9999, 9999));
y1 = _roundCoord(math.clamp(cmd.y1, -9999, 9999));
}
if (cmd.x2 !== undefined) {
x2 = math.clamp(cmd.x2, -9999, 9999);
y2 = math.clamp(cmd.y2, -9999, 9999);
x2 = _roundCoord(math.clamp(cmd.x2, -9999, 9999));
y2 = _roundCoord(math.clamp(cmd.y2, -9999, 9999));
}
if (cmd.type === MOVETO) {
if (!isNaN(x) && !isNaN(y)) {
Expand Down
8 changes: 8 additions & 0 deletions test/vgSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,14 @@ describe('A path', function () {
assert.equal(p.toSVG(), '<path d="M10 20L30 40Z"/>');
});

it('can probably round coordinates', function () {
var p;
p = new vg.Path();
p.moveTo(Math.PI, Math.E);
p.lineTo(100 / 3, 200 / 3);
assert.equal(p.toSVG(), '<path d="M3.142 2.718L33.333 66.667"/>');
});

it('can clone itself', function () {
var p, newP;
p = new vg.Path();
Expand Down

0 comments on commit 1310a5b

Please sign in to comment.