How do I change a canvas color with a click on html5?

-1

Excuse me but I would like to know how I can change a canvas color by the method of clicking on the drawing. It's for another type of work but I just want the method of clicking on the drawing and making an action.

    
asked by Lennox 01.05.2018 в 10:17
source

1 answer

0

window.onload = function(){
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d"); 
  ctx.fillStyle = "green";
  ctx.fillRect(10, 10, 200, 200);
  ctx.fill();
  canvas.addEventListener("click", function(e){
    if(e.clientX-canvas.offsetLeft > 10 && e.clientX-canvas.offsetLeft < 210){
      if(e.clientY-canvas.offsetTop > 10 && e.clientY-canvas.offsetTop < 210){
        ctx.fillStyle = "red";
        ctx.fillRect(10, 10, 200, 200);
        ctx.fill();
      }
    } 
  },false);
};
        
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Un canvas</title>
</head>
<body>
        <canvas width="1080" height="720" id="canvas"></canvas>
</body>
</html>

You have to add an eventListener and then look at what area of the screen you clicked on, this example superimposes a red square on the other.

    
answered by 01.05.2018 / 13:33
source