Update canvas on resize if not updating every frame

This commit is contained in:
Jake Archibald
2020-11-25 15:30:59 +00:00
parent fcef2b2d3e
commit 6fa13b919b

View File

@@ -193,6 +193,11 @@ export function startBlobAnim(canvas: HTMLCanvasElement) {
hasFocus = false; hasFocus = false;
}; };
new ResizeObserver(() => {
// Redraw for new canvas size
if (!animating) drawFrame(0);
}).observe(canvas);
addEventListener('focus', focusListener); addEventListener('focus', focusListener);
addEventListener('blur', blurListener); addEventListener('blur', blurListener);
@@ -201,6 +206,24 @@ export function startBlobAnim(canvas: HTMLCanvasElement) {
removeEventListener('blur', blurListener); removeEventListener('blur', blurListener);
} }
function drawFrame(delta: number) {
const canvasBounds = canvas.getBoundingClientRect();
canvas.width = canvasBounds.width * devicePixelRatio;
canvas.height = canvasBounds.height * devicePixelRatio;
const loadImgBounds = loadImgEl.getBoundingClientRect();
ctx.fillStyle = blobColor;
ctx.scale(devicePixelRatio, devicePixelRatio);
centralBlobs.draw(
ctx,
delta,
loadImgBounds.left - canvasBounds.left + loadImgBounds.width / 2,
loadImgBounds.top - canvasBounds.top + loadImgBounds.height / 2,
loadImgBounds.height / 2 / (1 + maxRandomDistance),
);
}
function frame(time: number) { function frame(time: number) {
// Stop the loop if the canvas is gone // Stop the loop if the canvas is gone
if (!canvas.isConnected) { if (!canvas.isConnected) {
@@ -223,21 +246,7 @@ export function startBlobAnim(canvas: HTMLCanvasElement) {
const delta = (time - lastTime) * deltaMultiplier; const delta = (time - lastTime) * deltaMultiplier;
lastTime = time; lastTime = time;
const canvasBounds = canvas.getBoundingClientRect(); drawFrame(delta);
canvas.width = canvasBounds.width * devicePixelRatio;
canvas.height = canvasBounds.height * devicePixelRatio;
const loadImgBounds = loadImgEl.getBoundingClientRect();
ctx.fillStyle = blobColor;
ctx.scale(devicePixelRatio, devicePixelRatio);
centralBlobs.draw(
ctx,
delta,
loadImgBounds.left - canvasBounds.left + loadImgBounds.width / 2,
loadImgBounds.top - canvasBounds.top + loadImgBounds.height / 2,
loadImgBounds.height / 2 / (1 + maxRandomDistance),
);
requestAnimationFrame(frame); requestAnimationFrame(frame);
} }