2

Basically, I have a code which shows where the user clicks on the canvas:

canvas.onclick = function(e){
    ctx.fillRect(e.clientX,e.clientY,10,10);
}

It works perfectly well if I include this in the code:

canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;

But I want the width and height of the canvas to be 200! Like this:

canvas.width = 200;
canvas.height = 200;

Whenever I try this, the clicks go all wrong! How can I have a width of 200 on my fullscreen canvas without resizing it or the window???

Helder Sepulveda
  • 15,500
  • 4
  • 29
  • 56
Jay
  • 23
  • 4

1 Answers1

0

I think that all you are missing is to substract the canvas offsets...

Here is a code example

var canvas = document.getElementById('can');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var ctx = canvas.getContext('2d');
ctx.fillRect(50, 50, 2, 2);

canvas.onclick = function(e) {
  r = 10
  x = e.clientX - canvas.offsetLeft - r
  y = e.clientY - canvas.offsetTop - r
  ctx.fillRect(x, y, r, r);
}
body {
  margin: 0
}
<canvas id="can" style="border:1px solid #000000;"></canvas>
Helder Sepulveda
  • 15,500
  • 4
  • 29
  • 56
  • I tried that...I dont think thats it, but thanks. – Jay Aug 16 '18 at 16:22
  • No.........What I need is a way to accurately show clicks on a canvas with a absolute size(pixels). The canvas should always take up the whole screen : width:100%; – Jay Aug 16 '18 at 22:36
  • 200px. But I need the canvas to take up the whole screen. (Fullscreen) – Jay Aug 16 '18 at 23:17