编写一个生成
指定输入数量圆球的程序:
JS.文档
得到了以下的页面:
然后每次输入指定的值后,页面就会很快显示一下球,然后变成空白。
之后我修改JS文档,取消点击事件触发,直接给了一个固定的值25.
然后页面就会得到指定的效果。
很抓狂,不知道什么原因,有哪位大大能指导一下萌新吗?
以下是文档(可直接粘贴复制):
JS:
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var width = canvas.width = window.innerWidth-20;
var height = canvas.height = window.innerHeight - 150;
var btnSub = document.querySelector("button#sub");
var btnRes = document.querySelector("button#reset");
var input = document.querySelector("input");
/*随机数函数
--------------------------------------------------------------------------------*/
function random(min,max) {
var num = Math.floor(Math.random()*(max-min)) + min;
return num;
}
/*新建小球对象函数
--------------------------------------------------------------------------------*/
function Ball(x, y, r, velx, vely, color) {
this.x = x;
this.y = y;
this.r = r;
this.color = color;
this.velx = velx;
this.vely = vely;
}
/*用canvas画小球函数
--------------------------------------------------------------------------------*/
Ball.prototype.draw = function() {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.r, 0, 2*Math.PI);
ctx.fill();
}
/*生成输入数量的小球
--------------------------------------------------------------------------------*/
var balls = [];
for(var i = 0; i < 25; i++) {
var x = random(0, width);
var y = random(0, height);
var r = random(10, 20);
var color = "rgb(" + random(0, 255) + "," + random(0, 255) + "," + random(0, 255) + ")";
var velx = random(-10, 10);
var vely = random(-10, 10);
balls[i] = new Ball(x, y, r, velx, vely, color);
balls[i].draw();
}
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>bouncing balls</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>"Bouncing Balls Test" By Chenxy</h1>
<form>
<label for="ballsNumber">Please enter the number of balls you want:</label>
<input type="text">
<button id="sub">submit</button>
<button id="reset">Reset</button>
</form>
<canvas></canvas>
<script src="main.js"></script>
</body>
</html>
ps:邀请的大神是系统推荐的,新人刚到,不懂规矩,如有冒犯,请狠狠地批评我~~~~~~~~~~~~~[/color[color=#800000]](鞭策我)