Canvas 星空背景(1)

Canvas 基础应用

html code



	
		
		canvas
		
	
	
		
		
	

javascript code

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var width = canvas.width;
var height = canvas.height;

function Spot(x, y, r, color, speed, alp, offset) {
	this.x = x;
	this.y = y;
	this.r = r;
	this.color = color;
	this.speed = speed;
	this.offset = offset;
	this.alp = alp;
	
	spotArr.push(this);
}

Spot.prototype.draw = function() {
	ctx.beginPath();
	ctx.fillStyle = this.color;
	ctx.globalAlpha = this.alp;
	ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
	ctx.fill();
}

Spot.prototype.update = function() {
	this.x += this.speed;
	this.alp -= this.offset;
}

function initSpot() {
	var r = (Math.random() * 1.4) + 0.1;
	var x = Math.random() * (width - r);
	var y = Math.random() * (height - r);
	var color = "aqua";
	var speed = (Math.random() * 10) + 2;
	var alp = Math.ceil(Math.random());
	var offset = (Math.random() * 0.01) + 0.01;
	new Spot(x, y, r, color, speed, alp, offset);
}

var spotArr = [];
for (var i = 0; i < 3000; i++) {
	initSpot();
}

function getColor() {
	var colorArr = ['0','1','2','3','4','5','6','7','8','9',
				    'a','b','c','d','e','f'];
	var color = '#';
	var colorIndex;
	for (var i = 0; i < 6; i++) {
		colorIndex = parseInt(Math.random() * (colorArr.length-1));
		color += colorArr[colorIndex];
	}
	return color;
}


setInterval(function() {
	ctx.clearRect(0, 0, width, height);
	
	for (var i = 0; i < spotArr.length; i++) {
		spotArr[i].update();
		spotArr[i].draw();
		
		if (spotArr[i].x > width) {
			spotArr[i].x = 0;
		}
		if (spotArr[i].alp < 0) {
			spotArr[i].alp = Math.ceil(Math.random());
		}
	}
}, 30);

效果

南无阿弥陀佛,祝你新年吉祥!

你可能感兴趣的:(javascript,Web,前端基础)