Home > Software engineering >  How to change a elements colour
How to change a elements colour

Time:12-11

I made a game of atari breakout of where i want the bricks to be multi coloured. I want it so that each individual brick has its own random colour that is randomly generated. I also dont want the other attributes such as the ball and the paddle to be targeted with this random colour change.

Here are the lines of code:

'use strict';

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 20;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 3;
var dy = -3;
var paddleHeight = 10;
var paddleWidth = 175;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
var brickRowCount = 11;
var brickColumnCount = 5;
var brickWidth = 73;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var score = 0;
var lives = 3;


var bricks = [];
for(var c=0; c<brickColumnCount; c  ) {
  bricks[c] = [];
  for(var r=0; r<brickRowCount; r  ) {
    bricks[c][r] = { x: 0, y: 0, status: 1 };
  }
}

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
document.addEventListener("mousemove", mouseMoveHandler, false);

function keyDownHandler(e) {
    if(e.key == "Right" || e.key == "ArrowRight") {
        rightPressed = true;
    }
    else if(e.key == "Left" || e.key == "ArrowLeft") {
        leftPressed = true;
    }
}

function keyUpHandler(e) {
    if(e.key == "Right" || e.key == "ArrowRight") {
        rightPressed = false;
    }
    else if(e.key == "Left" || e.key == "ArrowLeft") {
        leftPressed = false;
    }
}

function mouseMoveHandler(e) {
  var relativeX = e.clientX - canvas.offsetLeft;
  if(relativeX > 0 && relativeX < canvas.width) {
    paddleX = relativeX - paddleWidth/2;
  }
}
function collisionDetection() {
  for(var c=0; c<brickColumnCount; c  ) {
    for(var r=0; r<brickRowCount; r  ) {
      var b = bricks[c][r];
      if(b.status == 1) {
        if(x > b.x && x < b.x brickWidth && y > b.y && y < b.y brickHeight) {
          dy = -dy;
          b.status = 0;
          score  ;
          if(score == brickRowCount*brickColumnCount) {
            alert("YOU WIN, CONGRATS!");
            document.location.reload();
          }
        }
      }
    }
  }
}

function drawBall() {
  ctx.beginPath();
  ctx.arc(x, y, ballRadius, 0, Math.PI*2);
  ctx.fill();
  ctx.closePath();  
}
function drawPaddle() {
  ctx.beginPath();
  ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
  ctx.fill();
  ctx.closePath();
}
function drawBricks() {
  for(var c=0; c<brickColumnCount; c  ) {
    for(var r=0; r<brickRowCount; r  ) {
      if(bricks[c][r].status == 1) {
        var brickX = (r*(brickWidth brickPadding)) brickOffsetLeft;
        var brickY = (c * (brickHeight   brickPadding))   brickOffsetTop;    
        bricks[c][r].x = brickX;
        bricks[c][r].y = brickY;
        ctx.beginPath();
        ctx.rect(brickX, brickY, brickWidth, brickHeight);  
        ctx.fill();
        ctx.closePath();
      }
    }
  }
}
function drawScore() {
  ctx.font = "16px Arial";
  ctx.fillText("Score: " score, 8, 20);
}
function drawLives() {
  ctx.font = "16px Arial";
  ctx.fillText("Lives: " lives, canvas.width-65, 20);
}

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawBricks();
  drawBall();
  drawPaddle();
  drawScore();
  drawLives();
  collisionDetection();

  if(x   dx > canvas.width-ballRadius || x   dx < ballRadius) {
    dx = -dx;
  }
  if(y   dy < ballRadius) {
    dy = -dy;
  }
  else if(y   dy > canvas.height-ballRadius) {
    if(x > paddleX && x < paddleX   paddleWidth) {
      dy = -dy;
    }
    else {
      lives--;
      if(!lives) {
        alert("GAME OVER");
        document.location.reload();
      }
      else {
        x = canvas.width/2;
        y = canvas.height-30;
        dx = 3;
        dy = -3;
        paddleX = (canvas.width-paddleWidth)/2;
      }
    }
  }

  if(rightPressed && paddleX < canvas.width-paddleWidth) {
    paddleX  = 7;
  }
  else if(leftPressed && paddleX > 0) {
    paddleX -= 7;
  }

  x  = dx;
  y  = dy;
  requestAnimationFrame(draw);
}

function hardFunction(){
    ballRadius = 8;
    paddleWidth = 80;
    lives = 1;
    dx = 5;
    dy = -5;
};   

function mediumFunction(){
    ballRadius = 15;
    paddleWidth = 120;
    lives = 2;
    dx = 4;
    dy = -4;
};   

function easyFunction(){
    ballRadius = 20;
    paddleWidth = 175;
    lives = 3;
    dx = 3;
    dy = -3;
};  

draw();

console.log(ctx.fillStyle);
* {
    padding: 0;
    margin: 0;
  }
  canvas {
    background: #eee;
    display: block;
    margin: 0 auto;
  }
  button {
    border: none;
    color: gray;
    padding: 16px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px 0px 16.67%;
    transition-duration: 0.4s;
    cursor: pointer
  }

.buttonHard:hover {
  background-color: red;
  color: black;
}

.buttonMedium:hover {
  background-color: yellow;
  color: black;
}

.buttonEasy:hover {
  background-color: green;
  color: black;
}
    <canvas id="myCanvas" width="960" height="640"></canvas>

    <button id="button"  onclick="hardFunction();">Hard Mode</button>
    <button id="button"  onclick="mediumFunction();">Medium Mode</button>
    <button id="button"  onclick="easyFunction();">Easy Mode</button>

    <script src="script.js"></script>

CodePudding user response:

After the bricks are drawn reset the ctx.fillStyle back to black to not affect the paddle and ball color.

You can try it like this:

'use strict';

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 20;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 3;
var dy = -3;
var paddleHeight = 10;
var paddleWidth = 175;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
var brickRowCount = 11;
var brickColumnCount = 5;
var brickWidth = 73;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var score = 0;
var lives = 3;

// colors picked from here: https://hightekk.com/tools/swatch
const colors = [
  "#d1c4e9",
  "#b39ddb",
  "#9575cd",
  "#7e57c2",
  "#673ab7",
  "#5e35b1",
  "#512da8",
  "#4527a0",
  "#311b92",
  "#b388ff",
  "#7c4dff",
  "#651fff",
  "#6200ea",
];

function getRandomColor(){
  return colors[Math.floor(Math.random() * colors.length)];
}

var bricks = [];
for(var c=0; c<brickColumnCount; c  ) {
  bricks[c] = [];
  for(var r=0; r<brickRowCount; r  ) {
    bricks[c][r] = { x: 0, y: 0, status: 1, color: getRandomColor() };
  }
}

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
document.addEventListener("mousemove", mouseMoveHandler, false);

function keyDownHandler(e) {
    if(e.key == "Right" || e.key == "ArrowRight") {
        rightPressed = true;
    }
    else if(e.key == "Left" || e.key == "ArrowLeft") {
        leftPressed = true;
    }
}

function keyUpHandler(e) {
    if(e.key == "Right" || e.key == "ArrowRight") {
        rightPressed = false;
    }
    else if(e.key == "Left" || e.key == "ArrowLeft") {
        leftPressed = false;
    }
}

function mouseMoveHandler(e) {
  var relativeX = e.clientX - canvas.offsetLeft;
  if(relativeX > 0 && relativeX < canvas.width) {
    paddleX = relativeX - paddleWidth/2;
  }
}
function collisionDetection() {
  for(var c=0; c<brickColumnCount; c  ) {
    for(var r=0; r<brickRowCount; r  ) {
      var b = bricks[c][r];
      if(b.status == 1) {
        if(x > b.x && x < b.x brickWidth && y > b.y && y < b.y brickHeight) {
          dy = -dy;
          b.status = 0;
          score  ;
          if(score == brickRowCount*brickColumnCount) {
            alert("YOU WIN, CONGRATS!");
            document.location.reload();
          }
        }
      }
    }
  }
}

function drawBall() {
  ctx.beginPath();
  ctx.arc(x, y, ballRadius, 0, Math.PI*2);
  ctx.fill();
  ctx.closePath();  
}
function drawPaddle() {
  ctx.beginPath();
  ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
  ctx.fill();
  ctx.closePath();
}
function drawBricks() {
  for(var c=0; c<brickColumnCount; c  ) {
    for(var r=0; r<brickRowCount; r  ) {
      if(bricks[c][r].status == 1) {
        var brickX = (r*(brickWidth brickPadding)) brickOffsetLeft;
        var brickY = (c * (brickHeight   brickPadding))   brickOffsetTop;    
        bricks[c][r].x = brickX;
        bricks[c][r].y = brickY;
        ctx.beginPath();
        ctx.rect(brickX, brickY, brickWidth, brickHeight);  
        ctx.fillStyle = bricks[c][r].color;
        ctx.fill();
        ctx.closePath();
      }
    }
  }
  ctx.fillStyle = "#000000";
}
function drawScore() {
  ctx.font = "16px Arial";
  ctx.fillText("Score: " score, 8, 20);
}
function drawLives() {
  ctx.font = "16px Arial";
  ctx.fillText("Lives: " lives, canvas.width-65, 20);
}

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawBricks();
  drawBall();
  drawPaddle();
  drawScore();
  drawLives();
  collisionDetection();

  if(x   dx > canvas.width-ballRadius || x   dx < ballRadius) {
    dx = -dx;
  }
  if(y   dy < ballRadius) {
    dy = -dy;
  }
  else if(y   dy > canvas.height-ballRadius) {
    if(x > paddleX && x < paddleX   paddleWidth) {
      dy = -dy;
    }
    else {
      lives--;
      if(!lives) {
        alert("GAME OVER");
        document.location.reload();
      }
      else {
        x = canvas.width/2;
        y = canvas.height-30;
        dx = 3;
        dy = -3;
        paddleX = (canvas.width-paddleWidth)/2;
      }
    }
  }

  if(rightPressed && paddleX < canvas.width-paddleWidth) {
    paddleX  = 7;
  }
  else if(leftPressed && paddleX > 0) {
    paddleX -= 7;
  }

  x  = dx;
  y  = dy;
  requestAnimationFrame(draw);
}

function hardFunction(){
    ballRadius = 8;
    paddleWidth = 80;
    lives = 1;
    dx = 5;
    dy = -5;
};   

function mediumFunction(){
    ballRadius = 15;
    paddleWidth = 120;
    lives = 2;
    dx = 4;
    dy = -4;
};   

function easyFunction(){
    ballRadius = 20;
    paddleWidth = 175;
    lives = 3;
    dx = 3;
    dy = -3;
};  

draw();

console.log(ctx.fillStyle);
* {
    padding: 0;
    margin: 0;
  }
  canvas {
    background: #eee;
    display: block;
    margin: 0 auto;
  }
  button {
    border: none;
    color: gray;
    padding: 16px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px 0px 16.67%;
    transition-duration: 0.4s;
    cursor: pointer
  }

.buttonHard:hover {
  background-color: red;
  color: black;
}

.buttonMedium:hover {
  background-color: yellow;
  color: black;
}

.buttonEasy:hover {
  background-color: green;
  color: black;
}
<canvas id="myCanvas" width="960" height="640"></canvas>

    <button id="button"  onclick="hardFunction();">Hard Mode</button>
    <button id="button"  onclick="mediumFunction();">Medium Mode</button>
    <button id="button"  onclick="easyFunction();">Easy Mode</button>

    <script src="script.js"></script>

CodePudding user response:

Perhaps the desired result would also want to have some control over the randomized colors.

This basic example generate a random color in hsl with a randomized hue, but keep saturation and lightness the same at a set number.

If needed, further calculation based saturation and lightness can be added for coloring each brick with some patterns. The example includes a basic use of this by generating a gradient in lightness based on rows, but it is totally optional.

Example:

"use strict";

//            
  • Related