Canvas 代码数字雨

改版自:https://blog.csdn.net/qq_35068659/article/details/113800492

javascript code

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

canvas.width = window.screen.availWidth;
canvas.height = window.screen.availHeight;

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

function Text(str, x, y, size, 
			  color, alp, speed) {
	this.str = str;
	this.x = x;
	this.y = y;
	this.size = size;
	this.color = color;
	this.alp = alp;
	this.speed = speed;
	textArr.push(this);
}

Text.prototype.draw = function() {
	ctx.beginPath();
	ctx.font = this.size + 'px Arial';
	ctx.fillStyle = this.color;
	ctx.globalAlpha = this.alp;
	ctx.fillText(this.str, this.x, this.y);
}

Text.prototype.update = function() {
	this.y += this.speed;
}

function getStr() {
	var strArr = ['0','1','2','3','4','5','6','7','8','9',
				  'a','b','c','d','e','f'];
	var strIndex = parseInt(Math.random() * (strArr.length-1));
	return strArr[strIndex];
}

function getSpeed() {
	return parseInt(Math.random() * 10) + 10;
}

function getX(size) {
	return parseInt(Math.random() * (width - size));
}

function getSize() {
	return parseInt(Math.random() * 10) + 10;
}

function getAlp() {
	return Math.random() * (0.9) + 0.1;
}

function initText() {
	var str = getStr();
	var size = getSize();
	var y = 0;
	var x = getX(size);
	var color = getColor();
	var alp = getAlp();
	var speed = getSpeed();
	new Text(str, x, y, size, color, alp, speed);
}

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;
}

function changeObj(obj) {
	obj.y = 0;
	obj.speed = getSpeed();
	obj.str = getStr();
	obj.size = getSize();
	obj.x = getX(obj.size);
	obj.alp = getAlp();
}

var textArr = new Array();
for (var i = 0; i < 50; i++) {
	initText();
}

var animation = setInterval(function() {
	ctx.clearRect(0, 0, width, height);
	for (var i = 0; i < textArr.length; i++) {
		textArr[i].update();
		textArr[i].draw();
		
		if (textArr[i].y > height) {
			changeObj(textArr[i]);
		}
	}
}, 30);

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

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