首页 > 解决方案 > 在画布中创建随机形状

问题描述

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

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

随机粒子的图像

到目前为止的代码...

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>

标签: javascripthtmlcanvas

解决方案


在我得到答案之前,您显示的代码片段有很多错误。您可能想尝试解决这些问题。

无论如何,您应该使用 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
}

推荐阅读