用鼠标单击对象使画布对象消失

时间:2016-05-08 14:48:22

标签: javascript html css canvas

我的任务是随机绘制3-6个随机大小和随机颜色的矩形,然后每两秒添加一个,然后设置它们的动画,使它们移动。做完这个。剩下的就是用鼠标点击使矩形消失。

我的Html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Assignment 5</title>
    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/assignment5.css">
</head>
<body>
    <header>
      <h1>Assignment 5</h>
    </header>

<!--the height and width attributes size the canvas-->
<canvas id="canvas" width="1200" height="600"></canvas>


    <script src="js/assignment5.js" charset="utf-8"></script>
    <footer>
        Copyright &copy no one in particular...
    </footer>

我的Javascript

randomBoxes();


function getRandomColor() {         //Generates a random hex number for the color
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += (Math.random() * 16 | 0).toString(16);
    }
    return color;
}

  function boundryNum(theMin, theMax) {
     var theRange = (theMax - theMin) + 1;
     var randomNum = Math.floor((Math.random() * theRange) + theMin);
     return randomNum;
  }

  function drawbox() {
      var width = Math.floor(Math.random() * 200) +20;    //Random witdth 20-200
      var height = Math.floor(Math.random() * 200) + 20;  //Random height 20-200
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.fillRect(boundryNum(25,800),boundryNum(25,400),width,height);  //ctx.fillRect(x, y, width, height), where x and y are the coordinates of the starting place on the canvas.
      context.fillStyle = getRandomColor();
  }

  function randomBoxes(){
    var number = Math.floor(Math.random() * 5) + 1; //Three to six times....
    while(number >= 0){
    drawbox();
    number--;
    }
  setInterval(drawbox, 2000)
  }

我的Css

html{
  font-size: 14px;
}

header{
  background-color: black;
  height: 3rem;
  text-align: center;
}

h1{
  color: white;
}

h2{
  color:black;
}



body{
  background-color: black;
  padding-left: 30px;
  padding-right: 30px;
}

#canvas {
  position: absolute;
  top: 4.5rem;              //Starting point top-left.
  left: 1.5rem;
  width: 1000px;
  height: 500px;
  background: black;

  animation: move 3s ease infinite;
}

@keyframes move {
  50% {
     transform: translate(800px, 200px);  //(horizotal travel, verticle travel)
  }
}

footer{
  background-color: lime;
  text-align: center;
  color: black;
  margin-top: 800px;
}

我已经对此进行了两天的研究,我得出的是我应该在绘制时创建一个数组或每个矩形,并使用画布鼠标坐标遍历数组,与矩形坐标进行比较。使用画布图纸的clearRectangle属性清除矩形。我真的陷入了这项任务的最后一步。如果你知道它是如何完成的,我已经准备好了解如何去做。

作为本课程的最后一个项目,我希望通过加快矩形的创建并赋予其中一些渐变和阴影,将其变成一个越来越难的游戏。感谢。

1 个答案:

答案 0 :(得分:0)

我的解决方案是肯定的,创建每个对象的数组,并为它们提供ID。然后删除然后单击它们从数组中删除它们。 &#34; rectangle1.onclick&#34 ;.

您可能还希望每次都创建一个box对象并以此方式执行。而不仅仅是在画布上打印形状。