Skip to content

Commit

Permalink
fix(web): 🐛 fail to resize when canvas element is hidden (#454)
Browse files Browse the repository at this point in the history
* fix(web): 🐛 fail to resize when canvas element is hidden
  • Loading branch information
theashraf authored Jan 27, 2025
1 parent 7e67a20 commit 5b6ec2f
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/quick-actors-work.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@lottiefiles/dotlottie-web': patch
---

fix(web): 🐛 fail to resize when canvas element is hidden
6 changes: 4 additions & 2 deletions packages/web/src/dotlottie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -694,8 +694,10 @@ export class DotLottie {

const { height: clientHeight, width: clientWidth } = this._canvas.getBoundingClientRect();

this._canvas.width = clientWidth * dpr;
this._canvas.height = clientHeight * dpr;
if (clientHeight !== 0 && clientWidth !== 0) {
this._canvas.width = clientWidth * dpr;
this._canvas.height = clientHeight * dpr;
}
}

const ok = this._dotLottieCore.resize(this._canvas.width, this._canvas.height);
Expand Down
12 changes: 7 additions & 5 deletions packages/web/src/worker/dotlottie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ function getCanvasSize(
canvas: HTMLCanvasElement | OffscreenCanvas,
devicePixelRatio: number,
): { height: number; width: number } {
if (canvas instanceof OffscreenCanvas) {
return { width: canvas.width, height: canvas.height };
}
if (canvas instanceof HTMLCanvasElement) {
const { height: clientHeight, width: clientWidth } = canvas.getBoundingClientRect();

const { height, width } = canvas.getBoundingClientRect();
if (clientHeight !== 0 && clientWidth !== 0) {
return { width: clientWidth * devicePixelRatio, height: clientHeight * devicePixelRatio };
}
}

return { width: width * devicePixelRatio, height: height * devicePixelRatio };
return { width: canvas.width, height: canvas.height };
}

function generateUniqueId(): string {
Expand Down
25 changes: 25 additions & 0 deletions packages/web/tests/dotlottie.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2160,4 +2160,29 @@ describe.each([
});
});
});

test('doesn"t throw an error when resize is called and the canvas is not visible', async () => {
canvas.style.display = 'none';

const onLoad = vi.fn();
const onPlay = vi.fn();

dotLottie = new DotLottie({
canvas,
src,
autoplay: true,
});

dotLottie.addEventListener('load', onLoad);
dotLottie.addEventListener('play', onPlay);

await vi.waitFor(() => {
expect(onLoad).toHaveBeenCalledTimes(1);
expect(onPlay).toHaveBeenCalledTimes(1);
});

expect(() => dotLottie.resize()).not.toThrow();

canvas.style.display = 'block';
});
});

0 comments on commit 5b6ec2f

Please sign in to comment.