Skip to content

Commit

Permalink
feat: Use pixel content values from resize observer (#640)
Browse files Browse the repository at this point in the history
* Used 'new' pixel content values from resize observer

* docs: update deprecation hint

* refactor: move scalefactor

* refactor: inline `entry` variable

* Added feature detection

* Rounded pixel values

---------

Co-authored-by: Holger Stitz <[email protected]>
  • Loading branch information
dvmoritzschoefl and thinkh authored Nov 28, 2024
1 parent 78e0da2 commit ee71f95
Showing 1 changed file with 35 additions and 5 deletions.
40 changes: 35 additions & 5 deletions src/vis/vishooks/hooks/useCanvas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ export function useCanvas<ContextId extends '2d' | 'webgl' | 'bitmaprenderer' |
const [state, setState] = useSetState({
width: 0,
height: 0,
pixelContentWidth: 0,
pixelContentHeight: 0,
context: null as ContextId extends '2d'
? CanvasRenderingContext2D
: ContextId extends 'webgl'
Expand All @@ -26,15 +28,34 @@ export function useCanvas<ContextId extends '2d' | 'webgl' | 'bitmaprenderer' |
},
register: (element) => {
const observer = new ResizeObserver((entries) => {
if (entries[0]) {
const newDimensions = entries[0].contentRect;
const entry = entries[0];

if (entry) {
const newDimensions = entry.contentRect;

let pixelContentWidth = 0;
let pixelContentHeight = 0;

if ('devicePixelContentBoxSize' in entry && entry.devicePixelContentBoxSize?.[0]) {
// Feature is present
const { inlineSize, blockSize } = entry.devicePixelContentBoxSize[0];

pixelContentWidth = inlineSize;
pixelContentHeight = blockSize;
} else {
// Feature is not supported, round the canvas pixel buffer to an integer value that most likely snaps to the physical pixels
pixelContentWidth = Math.round(newDimensions.width * scaleFactor);
pixelContentHeight = Math.round(newDimensions.height * scaleFactor);
}

setState((previous) => {
if (previous.width === newDimensions.width && previous.height === newDimensions.height && previous.context) {
return previous;
}

return {
pixelContentWidth,
pixelContentHeight,
width: newDimensions.width,
height: newDimensions.height,
context: previous.context ? previous.context : (element.getContext(props?.contextId ?? '2d') as any),
Expand All @@ -54,9 +75,18 @@ export function useCanvas<ContextId extends '2d' | 'webgl' | 'bitmaprenderer' |
contentWidth: state.width,
contentHeight: state.height,

// Suggested dimensions for the canvas
width: state.width * scaleFactor,
height: state.height * scaleFactor,
/**
* @deprecated Use `pixelContentWidth` instead
*/
width: state.pixelContentWidth,

/**
* @deprecated Use `pixelContentHeight` instead
*/
height: state.pixelContentHeight,

pixelContentWidth: state.pixelContentWidth,
pixelContentHeight: state.pixelContentHeight,

context: state.context,
ratio: scaleFactor,
Expand Down

0 comments on commit ee71f95

Please sign in to comment.