0
canvas.onmousedown = function (event) {
  console.log(JSON.stringify(event)); // this logs {"isTrusted":true} 
};

same width

canvas.addEventListener("mousedown",  function (event) {
  console.log(JSON.stringify(event)); // this logs {"isTrusted":true} 
});

and when I try to log just the eventwithout parsing it the app crashes

سعيد
  • 1,547
  • 1
  • 14
  • 32

1 Answers1

1

That sandbox has a lot of code, I'm just going to focus on what you have here...

The mouse event object is complex and most likely JSON.stringify is taking a shortcut; and correct if you try to output the entire object it will be slow or it could crash like you describe, but there are other properties there, you can see it on the sample below.

var canvas = document.querySelector("canvas")
var ctx = canvas.getContext("2d")
ctx.fillStyle = "red"

for (let i = 10; i < 100; i += 10 )
  ctx.rect(i, i, 50, 50);
ctx.stroke();

canvas.onmousedown = function (event) {
  console.log(JSON.stringify(event));
  console.log(event.x, event.y);
  
  ctx.beginPath()
  ctx.arc(event.x, event.y, 5, 0, 8)
  ctx.fill();
};
body { margin: 0 }
<canvas id="canvas"></canvas>

You can see there I'm using event.x, event.y to draw circles at the point the user clicked.

You can read more about the available properties on the official documentation:
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent#properties


I imagine that your end goal is not to just output:
console.log(JSON.stringify(event)) there more must be something else you need those events to do...

Maybe best to ask a new question...
Explain there what are you trying to do in those events and what error are you getting if any.

Helder Sepulveda
  • 15,500
  • 4
  • 29
  • 56
  • thanks a lot this is really weird because I've logged the ```event``` object previously and this is the first time I faced this issue . – سعيد Jun 05 '22 at 23:44