在画布中创建随机形状

时间:2020-01-30 18:20:56

标签: javascript html canvas

我目前正在尝试创建一个随机浮动形状的画布动画。我目前正在使用这个Codepen(https://codepen.io/mikeddev/pen/xxboORV),它或多或少具有我要寻找的动画类型,但是我想弄清楚如何创建随机形状,例如下图所示,而不是圆形。

感谢大家对我如何实现这一愿景的任何指导。

Image of randomized particles

到目前为止的代码...

var canvas = document.querySelector('canvas');
// Dimensions Of The Canvas
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Get The Context 2d Dimensions
var c = canvas.getContext('2d');

var maxRadius = 40;
// var minRadius = 2;

// colors Array
var colorArray = ['#2C3E50','#E74C3C','#ECF0F1','#3498DB','#2980B9'];

window.addEventListener('resize', function() {
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;

	init();
})

function Circle(x, y, dx, dy, radius) {
	this.x = x;
	this.y = y;
	this.dx = dx;
	this.dy = dy;
	this.radius = radius;
	this.minRadius = radius;
	this.color = colorArray[Math.floor(Math.random() * colorArray.length)];

	this.draw = function() {
		c.beginPath();
		c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
		c.fillStyle = this.color;
		c.fill();
	}
	this.update = function() {
		if (this.x + this.radius > innerWidth || this.x - this.radius < 0) {
		this.dx = -this.dx;
		}
		if (this.y + this.radius > innerHeight || this.y - this.radius < 0) {
		this.dy = -this.dy;
		}
		this.x += this.dx;
		this.y += this.dy;

		this.draw();
	}
}

var circleArray = [];

function init() {
	circleArray = [];
	for (var i = 0; i < 300; i++) {
		var radius = Math.random() * 3 + 1;
		var x = Math.random() * (innerWidth - radius * 2) + radius;
		var y = Math.random() * (innerHeight - radius * 2) + radius;
		var dx = (Math.random() - 0.5);
		var dy = (Math.random() - 0.5);
		circleArray.push(new Circle(x, y, dx, dy, radius));
	}
}

function animate() {
	requestAnimationFrame(animate);
	c.clearRect(0, 0, innerWidth, innerHeight);

	for (var i = 0; i < circleArray.length; i++) {
		circleArray[i].update();
	}

}
init();
animate();
* {
	margin: 0;
	box-sizing: border-box;
}
html, body {
  margin: 0;
  height: 100%;
  overflow: hidden
}
body {
	padding: 0;
	text-align: center;
	background-color: #fff;
}
<canvas></canvas>

1 个答案:

答案 0 :(得分:2)

在我回答问题之前,您显示的代码段有很多错误。您可能要尝试修复这些问题。

无论如何, 您应该使用Math.random()制作随机数函数

function randomNumber(min,max) {
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}

然后可以使用if / then语句获得随机形状:

int rand = randomNumber(1,2)
if (rand === 1) {
    //code for circle
} else if (rand === 2) {
    //code for square
}  //etc

您可以根据需要选择任意数量的形状,使randomNumber()的最大值等于if / then语句的数量。

您还可以通过以下方法使某些人比其他人更普遍:

if (rand === 1 || rand === 2) {
    //code for shape
}