I started working with Konva recently, and everything was working. I opened the same HTML page on a monitor of 1920x1080 and at 150% zoom and found the data points array was coming wrong at this resolution.
layer.getContext('2d').getImageData(mousePos.x, mousePos.y, 1, 1).data;
At a specific point, it gives an array 242, 174, 165, 255
on a normal screen, whereas at this specific resolution, the values are coming wrong 238, 255, 0, 255
.
How do I fix this, is there a way I can do it? Any help is appreciated.
Konva is automatically adjusting canvas size, based on a pixel ratio of the current screen.
For example, on HDPI screen, like a retina display, window.devicePixelRatio = 2
. In that case Konva will create a 4x bigger canvas. If you stage is 500x500px, Konva will create 1000x1000px canvas. It is required for sharp display.
If you want to get pixel data under some point, you need to adjust position, based on pixel ratio. You can use this:
const layer = stage.children[0];
const canvas = layer.getNativeCanvasElement();
const pixelRatio = layer.getCanvas().getPixelRatio();
const { data } = canvas
.getContext('2d')
.getImageData(pos.x * pixelRatio, pos.y * pixelRatio, 1, 1);