Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在画布中创建随机形状_Javascript_Html_Canvas - Fatal编程技术网

Javascript 在画布中创建随机形状

Javascript 在画布中创建随机形状,javascript,html,canvas,Javascript,Html,Canvas,我目前正在尝试创建一个画布动画,随机形状浮动。我目前正在研究这个codepen(),它或多或少具有我正在寻找的动画类型,但是我想知道如何创建随机形状,如下图所示,而不是圆形 感谢大家对我如何实现这一愿景的指导 代码到目前为止 var canvas=document.querySelector('canvas'); //画布的尺寸 canvas.width=window.innerWidth; canvas.height=window.innerHeight; //获取二维维度的上下文 var

我目前正在尝试创建一个画布动画,随机形状浮动。我目前正在研究这个codepen(),它或多或少具有我正在寻找的动画类型,但是我想知道如何创建随机形状,如下图所示,而不是圆形

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

代码到目前为止

var canvas=document.querySelector('canvas');
//画布的尺寸
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;
//获取二维维度的上下文
var c=canvas.getContext('2d');
var maxRadius=40;
//var minRadius=2;
//颜色数组
var colorArray=['#2C3E50'、'#E74C3C'、'#ECF0F1'、'#3498DB'、'#2980B9'];
addEventListener('resize',function()){
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;
init();
})
函数圆(x,y,dx,dy,半径){
这个.x=x;
这个。y=y;
this.dx=dx;
this.dy=dy;
这个半径=半径;
这个.minRadius=半径;
this.color=colorArray[Math.floor(Math.random()*colorArray.length)];
this.draw=函数(){
c、 beginPath();
c、 圆弧(this.x,this.y,this.radius,0,Math.PI*2,false);
c、 fillStyle=this.color;
c、 填充();
}
this.update=函数(){
如果(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;
这个.draw();
}
}
var circleArray=[];
函数init(){
circleArray=[];
对于(变量i=0;i<300;i++){
var radius=Math.random()*3+1;
var x=Math.random()*(innerWidth-radius*2)+半径;
var y=Math.random()*(内部高度-半径*2)+半径;
var dx=(Math.random()-0.5);
var dy=(Math.random()-0.5);
推(新的圆(x,y,dx,dy,半径));
}
}
函数animate(){
请求动画帧(动画);
c、 clearRect(0,0,innerWidth,innerHeight);
对于(var i=0;i
*{
保证金:0;
框大小:边框框;
}
html,正文{
保证金:0;
身高:100%;
溢出:隐藏
}
身体{
填充:0;
文本对齐:居中;
背景色:#fff;
}

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

不管怎样, 您应该使用Math.random()创建一个随机数函数

然后可以使用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
}

函数替换为绘制所需形状的函数。我建议使用
moveTo
就像在《谢谢你的评论》中,朱利安,我认为从这里开始,可能会有一组10个预定义的形状,并按照你的建议使用一组预定义的参数更改它们的大小、颜色和旋转。
if (rand === 1 || rand === 2) {
    //code for shape
}