我们今天做了一个功课练习,我们需要用随机颜色创建矩形,并在带有开始和停止按钮的画布上定位。 我管理过它。
我们还需要通过单击删除选定的矩形。 这就是我被困住的地方。
*注意:这必须使用纯Javascript并且不使用jQuery。
这是我的代码:
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)
}