Skip to content

Commit

Permalink
fix(tileEngine): prevent negative sx/sy when map size is smaller than…
Browse files Browse the repository at this point in the history
… canvas size (#342)

* fix(tileEngine): prevent negative sx/sy when map size is smaller than canvas size

* typo

* fix permutation test
  • Loading branch information
straker authored Jan 26, 2023
1 parent 39f1d19 commit 5593943
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/tileEngine.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,11 +251,13 @@ class TileEngine {
// region, otherwise. Firefox and Safari won't draw it.
// @see http://stackoverflow.com/questions/19338032/canvas-indexsizeerror-index-or-size-is-negative-or-greater-than-the-allowed-a
set sx(value) {
this._sx = clamp(0, this.mapwidth - getCanvas().width, value);
let max = Math.max(0, this.mapwidth - getCanvas().width);
this._sx = clamp(0, max, value);
}

set sy(value) {
this._sy = clamp(0, this.mapheight - getCanvas().height, value);
let max = Math.max(0, this.mapheight - getCanvas().height);
this._sy = clamp(0, max, value);
}

set objects(value) {
Expand Down
68 changes: 68 additions & 0 deletions test/unit/tileEngine.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,74 @@ describe(
});
});

// --------------------------------------------------
// tileEngine.sx/sy
// --------------------------------------------------
describe('sx/sy', () => {
let tileEngine;
beforeEach(() => {
tileEngine = TileEngine({
tilewidth: 10,
tileheight: 10,
width: 70,
height: 70,
tilesets: [
{
image: new Image()
}
],
layers: [
{
name: 'test',
data: [0, 0, 1, 0, 0]
}
]
});
});

if (testContext.TILEENGINE_CAMERA) {
it('should set sx and sy', () => {
tileEngine.sx = 10;
tileEngine.sy = 20;

expect(tileEngine.sx).to.equal(10);
expect(tileEngine.sy).to.equal(20);
});

it('should clamp to min of 0', () => {
tileEngine.sx = -10;
tileEngine.sy = -20;

expect(tileEngine.sx).to.equal(0);
expect(tileEngine.sy).to.equal(0);
});

it('should clamp to max of canvas', () => {
tileEngine.sx = 1000;
tileEngine.sy = 2000;

expect(tileEngine.sx).to.equal(100);
expect(tileEngine.sy).to.equal(100);
});

it('should clamp to 0 if map size is smaller than canvas', () => {
tileEngine.mapwidth = 500;
tileEngine.mapheight = 400;
tileEngine.sx = 10;
tileEngine.sy = 20;

expect(tileEngine.sx).to.equal(0);
expect(tileEngine.sy).to.equal(0);
});
}
else {
it('should not have sx and sy properties', () => {
expect(tileEngine.sx).to.not.exist;
expect(tileEngine.sy).to.not.exist;
});
}
});

// --------------------------------------------------
// tileEngine.render
// --------------------------------------------------
Expand Down

0 comments on commit 5593943

Please sign in to comment.