Search code examples
javascripthtmlcanvashtml5-canvas

set different color on click function in Canvas


I want to change color our button are Press then canvas inside text color change.

var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');

context.font = '48px serif';
context.fillStyle = 'red'; // sets text color to red
context.fillText('Example text', 20, 65);

function ChangeColor() {
  console.log("dd", context);
  context.fillStyle = "blue";
}
<!doctype html>
<html>

<head>
  <style>
    #my-canvas {
      border: 1px solid gray;
    }
  </style>
</head>

<body>
  <canvas id="my-canvas" width="300" height="100"></canvas>
  <br>
  <button onClick="ChangeColor()"> Change Font Color Blue</button>
</body>

</html>


Solution

  • You need to clear the canvas and redraw everything using the "blue" color.

    You can clear the canvas using

    context.clearRect(0, 0, canvas.width, canvas.height);
    

    Here a working example for your use case:

    const canvas = document.querySelector('#my-canvas');
    const context = canvas.getContext('2d');
    
    draw("red");
    
    function ChangeColor() {
      clearCanvas();
      draw("blue");
    }
    
    function clearCanvas() {
      context.clearRect(0, 0, canvas.width, canvas.height);
    }
    
    function draw(color) {
      context.font = '48px serif';
      context.fillStyle = color; // sets text color to whatever was passed in
      context.fillText('Example text', 20, 65);
    }
    <!doctype html>
    <html>
    
    <head>
      <style>
        #my-canvas {
          border: 1px solid gray;
        }
      </style>
    </head>
    
    <body>
      <canvas id="my-canvas" width="300" height="100"></canvas>
      <br>
      <button onClick="ChangeColor()"> Change Font Color Blue</button>
    </body>
    
    </html>