vendredi 1 juin 2018

Delete a random canvas object

We got a homework Exercise today where we need to create rectangls in a random color and position on a canvas with a start and stop button. I've managed it.

We also need to delete a selected rectangle by clicking on it. This is where I am stuck.

* note: This MUST be with pure Javascript and without jQuery.

This is my code:

HTML:

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <title>Canvas Homwrok - Guy Zamir - 01/06/2018</title>
</head>

<body>
    <div class="container">
        <div class="row text-center">
        <button class="btn btn-success" onclick="game()">התחל</button>
        <button class="btn btn-danger" onclick="clearMe()">הפסק</button>
        </div>
    <canvas id="MyCanvas" width="800" height="800"></canvas>
    </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>    
<script src="assets/js/functions.js"></script>
</body>
</html>


Javascript:

   var twoDimention;
MyCanvas;

var randomNumX;
var randomNumY;
var randomNum;

var Interval;
function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

function game(){
var boxes = [];

MyCanvas = document.getElementById("MyCanvas");
twoDimention = MyCanvas.getContext("2d");
        Interval = setInterval(function () {
         boxes.push(randomNum);

    for(i=0; i<boxes.length; i++){
//        twoDimention.clearRect(randomNumX, randomNumY, randomNum, randomNum)

        randomNumX = Math.ceil((Math.random() * 800)+1);
        randomNumY = Math.ceil((Math.random() * 800)+1);
        randomNum = Math.ceil((Math.random() * 150)+10);

        twoDimention.fillStyle = getRandomColor();
        twoDimention.fillRect(randomNumX, randomNumY, randomNum, randomNum);

    }

             }, 1000);   

}


function clearMe(){
  clearInterval(Interval)
}




Aucun commentaire:

Enregistrer un commentaire