【发布时间】:2016-05-08 23:02:09
【问题描述】:
我的任务是随机绘制 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 © 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 属性来清除矩形。我真的被困在这个任务的最后一步。如果你知道它是怎么做的,我已经准备好学习如何去做了。
作为我这门课的最后一个项目,我想通过加快矩形的创建速度并为其中的一些提供渐变和阴影,将它变成一个难度越来越高的游戏。谢谢。
【问题讨论】:
-
对不起,在我原来的评论中我错过了你在 CSS 中做动画。您可以将单击处理程序附加到框以将其删除,但我认为您可能希望切换到使用 JS 制作动画并使用数组来管理您的框。我认为这会让你更好地控制运动风格。
-
你的设计有点不寻常。 开始提示: 通常的设计是将所有矩形放在一个数组中,然后在画布上绘制所有矩形。画布矩形无法移动,但您可以擦除画布并在新位置重新绘制所有矩形(创建移动效果)。通过订阅画布的
mousedown事件来监听用户点击事件。如果鼠标在任何带有mousex>rectx && mousex<rectx+width && mousey>recty && mousey<recty+rectheight的矩形上,点击测试。命中时,从数组中删除矩形或将该矩形标记为“不绘制”。
标签: javascript html css canvas