Canvas 新年数字雨

Canvas 基础应用

html code



	
		
		canvas learn
		
	
	
		
		
	

javascript code

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

canvas.width = 500;
canvas.height = 600;

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 initText() {
	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));
	var str = strArr[strIndex];
	var size = parseInt(Math.random() * 10) + 10;
	var y = 0;
	var x = parseInt(Math.random() * (canvas.width - size));
	var color = getColor();
	var alp = Math.random() * (0.9) + 0.1;
	var speed = parseInt(Math.random() * 10) + 10;
	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;
}

var textArr = new Array();
for (var i = 0; i < 20; 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 > canvas.height) {
			textArr.splice(i, 1);
		}
	}
	if (textArr.length === 0) {
		clearInterval(animation);
	} 
}, 30);

:如果要无限下雨,则改变代码逻辑为

textArr.splice(i, 1); => textArr[i].y = 0;

对象的 update 函数可以添加更多的逻辑,来实现绚丽的效果

修改版链接:https://blog.csdn.net/qq_35068659/article/details/113800853

效果

Canvas 新年数字雨_第1张图片

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

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