JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
var canvas = document.getElementById('mainc');
var context = canvas.getContext('2d');
canvas.width = $(window).width();
canvas.height = $(window).height();
var started = false;
var bubbleCount = 0;
var bubs = [];
$(document).ready(function() {
bubbleCount = $('#range').val();
start();
});
var toggle = function() {
if (started == true) {
stop();
} else {
bubbleCount = $('#range').val();
start();
}
}
var stop = function() {
clearInterval(main);
clearCanvas();
bubs = [];
started = false;
}
var start = function() {
started = true;
createBubbles();
drawBubbles(bubs);
main = setInterval(function() {
clearCanvas();
moveBubbles();
drawBubbles();
}, 16);
}
var createBubbles = function() {
for (i = 0; i < bubbleCount; i++) {
var vary = codes();
bubs.push(new bubble(vary.centerX, vary.centerY, vary.radius, vary.vx, vary.vy));
}
}
var codes = function() {
var centerX = Math.floor((Math.random() * canvas.width) + 1);
if (centerX > canvas.width - 10) {
centerX = centerX - 10;
}
if (centerX < 10) {
centerX = centerX + 10;
}
var centerY = Math.floor((Math.random() * canvas.height) + 1);
var radius = Math.floor((Math.random() * 10) + 3);
var vx = Math.floor((Math.random() * 10) - 5);
var vy = -Math.floor((Math.random() * 100) + 1);
return {
centerX: centerX,
centerY: centerY,
radius: radius,
vx: vx,
vy: vy
};
}
function bubble(centerX, centerY, radius, vx, vy) {
this.centerX = centerX;
this.centerY = centerY;
this.radius = radius;
this.vx = vx;
this.vy = vy;
return this;
}
var drawBubbles = function() {
$.each(bubs, function(i, val) {
context.beginPath();
context.arc(val.centerX, val.centerY, val.radius, 0, 2 * Math.PI, false);
context.fill = '#6ECFF6'
context.lineWidth = 1;
context.shadowColor = '#555555';
context.shadowBlur = 4;
context.shadowOffsetX = 2;
context.shadowOffsetY = 2;
context.strokeStyle = '#7D7D7D';
context.stroke();
});
}
function clearCanvas() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
var moveBubbles = function() {
$.each(bubs, function(i, val) {
val.centerY += (val.vy / 50);
if (val.centerY < 0) {
val.centerY = canvas.height + 15;
}
val.centerX += (val.vx / 50);
if (val.centerX - val.radius < 0) {
val.vx = -val.vx;
}
if (val.centerX + val.radius > canvas.width) {
val.vx = -val.vx;
}
});
}
var bubblechange = function(value) {
if (value > bubs.length) {
var vary = codes();
bubs.push(new bubble(vary.centerX, vary.centerY, vary.radius, vary.vx, vary.vy));
bubblechange(value);
}
if (value < bubs.length) {
bubs.pop();
bubblechange(value);
}
}