Given rectangular shape should get that color

<!DOCTYPE html>
<html>
<head>
	<title>Canvas</title>
	<style>
		canvas {border: 1px solid black; }
    </style>
</head>
<body>
	<h1>Canvas</h1>
	<canvas width="300" height="200" id="myCanvas"></canvas>
 <script>

 	var canvas = document.getElementById("myCanvas")
 	var ctx = canvas.getContext("2d");
  
        ctx.fillStyle = "rgb(200, 0, 0)";
        ctx.fillRect(50, 40, 100, 30);

        
        ctx.fillStyle = "rgb(100, 100, 200)";
        ctx.fillRect(50, 140, 100, 30);

     if (color1==red) {
  	    Change color of the box to red}
  	 Else if ( color1== green){
  		Change color to green}
  	 Else{no Change}

   </script>
</body>
</html>

can any one help me to give color in rectangle

is this what you wrote in your code? If so, you typically didn’t select anything.

can u help me please

i was asking if that is how you wrote it in your code.

You didn’t select any element.

You could select the element by its tag name, id, class, attribute…
for example,

<div class = 'mydiv'> my rectangle </div> and then you select it:

.mydiv {
	border: 4px solid black;
	background-color: red;
}

Use the background-color property.

 if (color1==red) {
  	    Change color of the box to red}
  	 Else if ( color1== green){
  		Change color to green}
  	 Else{no Change}

this is example i want to fill color according to this in that code

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).


@samolex if you want to keep helping here now the code is visible in the first post

Write a script to select one of the color and  Given rectangular shape should get that color. If both selected then I shoud display - " Select only one color"

“can anyone help me”

Here you’ve got couple of options. You can style the classes with CSS and use JavaScript to change the class name or even hard-code the style.

Something like:

const elementName = document.querySelector('element');
And then someName.className = 'someClass';

Or sth like someName.style.backgroundColor = 'red';

There are other options though…