Sinan AKYAZICI
Sinan AKYAZICI

Reputation: 3952

How to trigger click event of a button in Canvas by using JavaScript?

I googled this topic during hours but I couldn't get any answer. I'm trying to trigger click event of a button in Canvas. The source code looks like below:

<body>
<div class="webgl">
    <div id="unity">
        <canvas id="canvas"></canvas>
    </div>
</div></body>

I cannot reach the button element. I don't know that there is a solution. Can you help me please ?

Upvotes: 0

Views: 1637

Answers (1)

We can't attach event handlers to the paths drawn inside canvas, but we can attach event to the whole canvas, get the x, y co-ordinates and find out whether the user clicked on a button inside canvas. You can run the following code, in which I have created 2 buttons and attached a click handler on whole canvas element. Inside that handler I am collecting the event co-ordinates and using some math to find out whether the click is actually happened on the button or not.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// create circles to draw
const buttons = [
  {
    x: 40,
    y: 40,
    width: 100,
    height: 40,
    color: 'rgb(255,0,0)',
    text: 'Button 1'
  },
  {
   x: 40,
    y: 100,
    width: 100,
    height: 40,
    color: 'rgb(255,0,255)',
    text: 'Button 2'
  }
];

buttons.forEach(b => {
  ctx.beginPath();
  ctx.rect(b.x, b.y, b.width, b.height);
  ctx.fillStyle = b.color;
  ctx.fill();
  ctx.fillStyle = 'white';
  ctx.font = "14px Arial";
  ctx.fillText(b.text, b.x + b.width / 4, b.y + b.height / 1.6);
});

function isIntersect(pos, btn){
   if( 
     (pos.x >= btn.x && pos.x < btn.x + btn.width) &&
     (pos.y >= btn.y && pos.y < btn.y + btn.height)
    )
     return true;
  return false;
}

canvas.addEventListener('click', (e) => {
  const pos = {
    x: e.clientX,
    y: e.clientY
  };
  buttons.forEach((b,i) => {
    if (isIntersect(pos, b)) {
      alert('click on circle: ' + i);
    }
  });
});
body {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

canvas{
  border: 1px solid red;
}
<canvas id="canvas" />

Upvotes: 2

Related Questions