Menu

1 / 2

Map pointer coordinates into the canvas drawing buffer

DEV Community: frontend·David Miller·about 16 hours ago
#TWmmD1Ks
#devtofrontend#devto#dev#canvas#buffer
Reading 0:00
15s threshold

Convert the pointer position into drawing-buffer coordinates before drawing a marker on a resized canvas. The event reports viewport coordinates, while the drawing buffer has its own width and height.

For a canvas displayed at half its buffer width, one CSS pixel covers two buffer pixels. Subtracting the canvas position gives a local CSS coordinate. Multiply that value by the buffer-to-display ratio before drawing a marker or choosing a crop boundary.

function canvasPoint ( canvas , event ) { const rect = canvas . getBoundingClientRect (); if ( rect . width === 0 || rect . height === 0 ) return null ; return { x : ( event . clientX - rect . left ) * canvas . width / rect . width , y : ( event . clientY - rect . top ) * canvas . height / rect . height }; }

Enter fullscreen mode

Exit fullscreen mode

This example assumes an axis-aligned canvas with no CSS border or padding and no rotation or skew. Put a decorative border on a wrapper.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.