p5.j​​s –平滑变形随机形状

时间:2018-06-29 23:12:17

标签: javascript random interpolation p5.js

首先,我是js和p5.js的初学者。 我对这个程序的目标是一个平滑变形的随机形状。我对calculateShape()函数和drawShape()函数感到满意,但是当涉及到变形(updateShape())时,它确实很难看。我认为将当前数组保存到临时数组中,然后循环遍历该数组,并向每个索引的每个x和y添加一个随机数,然后在该索引处替换旧的x和y,这可能是个好主意。 主要问题是,它总是在屏幕上添加新的形状,而不是更改现有形状的顶点的值。你们中的任何人都可以给我提示或指出我的错误吗( s)?谢谢!

var c1;
var c2;
var c3;
var centerX;
var centerY;
var fb;
var radius;
var angle;
var shape = [];
var temp;


/*function to calculate the inital shape*/
function calculateShape() {
    //calculate coordinates and save into array
    for (var i = 0; i < fb; i++) {
        var x = cos(angle * i) * radius + random(-77,77);
        var y = sin(angle * i) * radius + random(-77,77);
        var v = createVector(x, y);
        shape.push(v);
    }
}

/*function for morphing the shape*/
function updateShape() {
    var temp = shape;
    for (var i = 0; i < shape.length - 1; i++) {
        var x = temp[i].x + random(-1, 1);
        var y = temp[i].y + random(-1, 1);
        var p = temp[i];
        var v = createVector(x, y);
        shape.splice(p,1);
        shape.push(v);    
    }
}


/*function for drawing the shape on the screen*/
function createShape(){
    beginShape();
    curveVertex(shape[shape.length-1].x, shape[shape.length-1].y);
    for (var i = 0; i < shape.length; i++){
        curveVertex(shape[i].x, shape[i].y);
    }
    curveVertex(shape[0].x, shape[0].y);
    endShape(CLOSE);
}




function setup() {
    createCanvas(windowWidth, windowHeight);
    smooth();
    background(250);
    //frameRate(2);

    // defining possible colors
    c1 = color(0, 196, 181, 235); 
    c2 = color(50, 227, 232, 235);
    c3 = color(248, 49, 62, 255);
    var colors = [c1, c2, c3];


    //center of the window
    centerX = windowWidth/2;
    centerY = windowHeight/2;

    //defining all variables
    fb = 8; 
    angle = radians(360 / fb);
    radius = random(120, 140);

    //calling thefunction that initalises the shape
    calculateShape();
}


function draw() {
    translate(centerX, centerY);


    blendMode(BLEND);
    fill(c3);
    noStroke();


    createShape();
    updateShape();    
}

1 个答案:

答案 0 :(得分:0)

  

主要问题是,它总是在屏幕上添加新形状,而不是更改现有形状的顶点值。

当然,您只需要在重新绘制之前清除屏幕即可。因此,请使用background(250)setup中的draw重置背景。