Search code examples
javascriptcanvasmousesandbox

How to detect where a stretched canvas was clicked?


I have a canvas that is stretched out since I am making a sandbox game. I can not use the normal method of detecting the pixel on the page a canvas is clicked because I need to know which stretch pixel was clicked. Hopefully this makes sense?


Solution

  • All you have to do is scale the position based on your current canvas size and original canvas size.

    function scaleCursorPoint(int mouseX, int mouseY, ctx) {
        return {
            x: mouseX * (ctx.canvas.width / ctx.width), 
            y: mouseY * (ctx.canvas.height / ctx.height) 
       };
    }
    

    ctx (which is gotten with canvas.getContext('2d') has the width of the original unstretched. ctx.canvas gets the original canvas DOM element. ctx.canvas.width is the size of the DOM element (the stretched size).

    Divide the two and you get the scale value. Then just multiple that scale value with the points you got and you're good