Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>These</p> <pre><code>canvas.width = 300; canvas.height = 480; </code></pre> <p>is the actual size of the <em>bitmap</em> canvas uses. Everything you do to canvas is relative to these.</p> <p>and these</p> <pre><code>canvas.style.width = "300px"; canvas.style.height = "480px"; </code></pre> <p>are the <em>display</em> size in the browser of the canvas <em>element</em> (not the bitmap). If the size differs from the bitmap size the bitmap size is resized for display purpose only. The bitmap is still of the same size internally. Think of the canvas being equal to an image difference being canvas is editable, image is not.</p> <p>This means all operations you do to canvas <em>element</em> has to be scaled to fit the bitmap size in case they are not the same, including mouse/touch positions, because the x and y position you get from the mouse event is relative to the <em>element</em>.</p> <p>Ie. clicking at point [600, 600] on the element would also be [600, 600] on the bitmap, but since the bitmap is only half the size the point would be outside the bitmap.</p> <p>Likewise, clicking at point [300, 300] on the canvas element would also be [300, 300] on the bitmap, but on the bitmap it would be at the right edge so when the pixel here is changed that pixel is scaled to display size which would end up at the edge too and not where the point was clicked initially.</p> <p>Try to scale your click position to get the correct pixel like this:</p> <p>Put these in global (and update in canvas resize if needed):</p> <pre><code>xScale = canvas.width / canvas.offsetWidth; yScale = canvas.height / canvas.offsetHeight; </code></pre> <p>And in your mouse event handler:</p> <pre><code>function handleMouse(e) { var r = canvas.getBoundingClientRect(), x = (e.clientX - r.left) * xScale ; y = (e.clientY - r.top) * yScale ; ... rest of code goes here ... } </code></pre> <p>(it's about the same code for touch, just use the touch point collection instead).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload