Give each shape on HTML5 Canvas a random colour

css random color
random color generator javascript
canvas background color
canvas fill color
canvas fillrect color
html canvas background
html rectangle fill color
canvas fill circle

Trying to create a page of squares, each with a different colour. So far I have a random colour generator which works, but so far it sets every square to the same random colour each time the page loads, just trying to figure out a way to give each square a different random colour.

I've tried using functions to create a different colour but that hasn't worked very well, here is the code for my random number generator:

var red = Math.floor(Math.random()* 255);
var green = Math.floor(Math.random() * 255);
var blue = Math.floor(Math.random() * 255);

And here is the code for one of my squares (all of them have the same code, just different co-ordinates)

ctx.rect(820, 50,100,100);
ctx.closePath();
ctx.fillStyle = "rgb("+red+","+green+"," +blue+" )";    
ctx.fill();

The entire code is here:

<html>
<canvas id="canvas1" height="768" width="1024" style="border: 1px solid #000000;"></canvas>

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

  var red = Math.floor(Math.random() * 255);
  var green = Math.floor(Math.random() * 255);
  var blue = Math.floor(Math.random() * 255);

  ctx.beginPath();
  ctx.rect(70, 50, 100, 100);
  ctx.closePath();
  ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
  ctx.fill();

  ctx.rect(220, 50, 100, 100);
  ctx.closePath();
  ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
  ctx.fill();

  ctx.rect(370, 50, 100, 100);
  ctx.closePath();
  ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
  ctx.fill();

  ctx.rect(520, 50, 100, 100);
  ctx.closePath();
  ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
  ctx.fill();

  ctx.rect(670, 50, 100, 100);
  ctx.closePath();
  ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
  ctx.fill();

  ctx.rect(820, 50, 100, 100);
  ctx.closePath();
  ctx.fillStyle = "rgb(" + red + "," + green + "," + blue + " )";
  ctx.fill();
</script>


</html>

This only sets the colours once before you draw your rectangles;

var red = Math.floor(Math.random()* 255);
var green = Math.floor(Math.random() * 255);
var blue = Math.floor(Math.random() * 255);

You could create a function that does this and returns the values;

function getRandomColour(){
  var red = Math.floor(Math.random()* 255);
  var green = Math.floor(Math.random() * 255);
  var blue = Math.floor(Math.random() * 255);

  return "rgb("+red+","+green+"," +blue+" )";  
}

Alternatively, you could pre-define your rectangle values in an array and loop over them to draw your rectangles. Would be less code.

var canvas = document.getElementById("canvas1");
    var ctx = canvas.getContext("2d");


function getRandomColour(){
  var red = Math.floor(Math.random()* 255);
  var green = Math.floor(Math.random() * 255);
  var blue = Math.floor(Math.random() * 255);

  return "rgb("+red+","+green+"," +blue+" )";  
}

ctx.fillStyle = getRandomColour();
ctx.fillRect(70,50,100,100);

ctx.fillStyle = getRandomColour();
ctx.fillRect(10,10,100,100);
<canvas id="canvas1"></canvas>

javascript, Trying to create a page of squares, each with a different colour. So far I have a random colour generator which works, but so far it sets every square to the same​  In the previous post, you have learned about drawing shapes with HTML5 canvas. You have also learned how to fill CSS colors on the shapes by setting the fill color property. Along with the CSS color values, you can also set the fill color to a gradient object.

This is what you need to do:

 var canvas = document.getElementById("canvas1");
    var ctx = canvas.getContext("2d");
    function RandColor() {
      var letters = '0123456789ABCDEF';
      var color = '#';
      for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }
        

        ctx.beginPath();
        ctx.fillStyle = RandColor();
        ctx.fillRect(70,50,100,100);
        ctx.fillStyle = RandColor();
        ctx.fillRect(220, 50,100,100);
<canvas id="canvas1" />

Draw a circle filled with random color squares on HTML5 canvas, When we need to fill a circle with 1x1 pixels, all with different colors in a browser, How can I generate random number in a given range in Android? Draw a circle filled with random color squares on HTML5 canvas removes pixels outside next shape Ctx1.globalCompositeOperation = 'destination-in';  This attribute represents the color or style to use inside the shapes. 2: strokeStyle. This attribute represents the color or style to use for the lines around shapes.

You must want to create functions to easily add objects, like this:

// Add function to pick random rgb values
function getRandomRGB() {
  var r = Math.floor(Math.random() * 255);
  var g = Math.floor(Math.random() * 255);
  var b = Math.floor(Math.random() * 255);
  return "rgb(" + r + "," + g + "," + b + ")";
}

// You may want to add this other function to simplify your code, too
function addFilledRect(arg1, arg2, arg3, arg4) {
  // Inside this function, we're using the ctx variable from outside
  ctx.fillStyle = getRandomRGB();       // Call the function to get a random rgv color
  ctx.fillRect(arg1, arg2, arg3, arg4); // Create the filled rectangle
}

var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");

// Then, you can call the above function multiple times
addFilledRect(70, 50, 100, 100);
addFilledRect(220, 50, 100, 100);
addFilledRect(370, 50, 100, 100);
addFilledRect(520, 50, 100, 100);
addFilledRect(670, 50, 100, 100);
addFilledRect(820, 50, 100, 100);
<html>
  <canvas id="canvas1" height="768" width="1024" style="border: 1px solid #000000;"></canvas>
</html>

Generating Random Colors, Give your designs some flair by using the code here to generate random We know a hex color value is made up of six characters with each character being  To create a rectangle using HTML5 Canvas, we can use the rect() method rather than constructing the shape with 4 connecting lines. An HTML5 Canvas rectangle is positioned with x and y parameters, and is sized with width and height parameters. The rectangle is positioned about its top left corner.

JavaScript Math: Create random background color, DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JavaScript function to create random background color</title> </head> <body>  Before we can start drawing, we need to talk about the canvas grid or coordinate space. Our HTML skeleton from the previous page had a canvas element 150 pixels wide and 150 pixels high. To the right, you see this canvas with the default grid overlayed. Normally 1 unit in the grid corresponds to 1 pixel on the canvas.

Applying styles and colors, If we want to apply colors to a shape, there are two important Each of the following examples describe the same color. accept CSS rgba color values, we can use the following notation to assign a More exactly, the miter limit is the maximum allowed ratio of the extension length (in the HTML canvas,  The random () method returns a random number from 0 (inclusive) up to but not including 1 (exclusive). Browser Support. Technical Details. A Number, representing a number from 0 up to but not including 1. JavaScript Version: Return a random number between 1 and 10: Math.floor( (Math.random() * 10) + 1); Try it Yourself »

HTML canvas fill() Method, Draw two 150*100 pixels rectangles. Fill one with a red color and the other with a blue color: YourbrowserdoesnotsupporttheHTML5canvastag. JavaScript: var c =​  Applying colors with the HTML5 canvas tag. To specify a fill or stroke color in the canvas tag, you can use the same color tools you use in CSS and HTML:. Six-digit hex values: The six-digit hexadecimal scheme commonly used in CSS uses two digits each for red, green, and blue.

Comments
  • In order to assess your problem I need to have a look at your entire JS code in its entirety. I am curious on how you set your colour variables
  • I added the entire code to the bottom of the post for you, hope it helps
  • Math.random() is only called once for each colour value (r, g and b) before you draw all of your rectangles, meaning they are the same for each rectangle below. You'd either need to reset your variables again, draw your rectangles in a loop and use the key to randamise the number, or create a function to assign the colour each time a rectangle is drawn.
  • That makes sense, I've been trying to do the function thing for every time the rectangle is drawn but I cant get it to work. Any ideas? Thanks anyway
  • I'm going to roll back your question. You must not update your question using the answers elements. And if you want to set it as "solved", please accept one of the answer by ticking it. Please take a look at my answer too, I've tried to enhance things to make the code shorter!
  • So i've done exactly how you said with the function, but its still creating 6 squares that are the same colour? I see you've added some more code beneath, would I need to add that or is that for the looping method (which I haven't used yet)
  • It was for the looping code, which I decided to abandon as it was probably out of scope for the question. It should have worked fine, can you update the code in your question so I can see what you have now?
  • No worries, I've updated the question. Sorry for this, its probably a very simple problem and i'm just missing something obvious
  • Don't worry, it's not. I've got the same issue. It looks like the Math.random isn't as random as I thought it was.
  • @Beltyboy118 it's because you shouldn't create the ctx.rect like this look at my answer to see how to do it