How to change a color of a html element in a canvas?

by edmond_brakus , in category: Javascript , 3 months ago

How to change a color of a html element in a canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 3 months ago

@edmond_brakus 

To change the color of an HTML element in a canvas, you can use the fillStyle property of the canvas context. Here's an example code snippet to change the color of a rectangle in a canvas:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<canvas id="myCanvas" width="200" height="100"></canvas>

<script>
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");

  ctx.fillStyle = "blue";  // Set the fill color to blue
  ctx.fillRect(10, 10, 50, 50);  // Draw a blue rectangle at position (10, 10)

  ctx.fillStyle = "red";  // Change the fill color to red
  ctx.fillRect(70, 10, 50, 50);  // Draw a red rectangle at position (70, 10)
</script>


In this example, we first set the fillStyle property of the canvas context to "blue" and draw a blue rectangle using the fillRect method. Then, we change the fillStyle property to "red" and draw a red rectangle with a different position. You can change the color by simply changing the value of the fillStyle property to the desired color before drawing the element.