簡體   English   中英

如何在 p5.js 中的另一個 object 中繪制對象數組?

[英]How can I draw an array of objects inside another object in p5.js?

我在 p5.js 中學習 JS,我需要一些幫助:我有一個對象數組(只是一些以隨機模式不斷移動的行),我想將它們保持在另一個 object 的邊界內,在這個案例,一個圓圈。 我試圖用 createGraphics function 來解決這個問題,但它不起作用。

行數組稱為“linhas”(object class 位於另一個名為“linhas.js”的文件中,第二個背景為“fundo2”,圓圈為“circulo”。代碼如下:

let linhas = [];
let fundo2;

function setup() {
  createCanvas(400, 400);
  pixelDensity(1);
  fundo2 = createGraphics (400,400);
  for (let i = 0; i < 100; i++){
  let x = random(0, 400);
  let y = random(0, 400);
  let z = random(0, 400);
  let w = random(0, 400);
  linhas[i] = new Linha(x, y, z, w);
  }
}

function draw() {
sol();
tracos();
}

function tracos() {
 for (let linha of linhas) {
  linha.display();
  linha.tremer();
 }
}

function sol() {
image(fundo2,0,0);
fundo2.noStroke();
fundo2.circle(200,200,250);
}

如果你們想更好地了解我的嘗試,p5.js 的 web 編輯器的鏈接是: https://editor.p5js.org/dolivetro/sketches/NZ2FlsPwx

提前致謝! 我的 p5.js 項目

您基本上有三個選項 1)根據每條線與要在其中繪制的圓之間的交點進行數學計算以計算每條線的起點和終點; 2)將線條繪制到單獨的上下文中,將內容復制到圖像,然后使用p5.Image.mask function; 或 3) 將線條繪制到單獨的上下文中,然后使用erase() function 或blendMode(REMOVE)清除不在圓圈內的上下文部分(這也需要額外的蒙版形狀)。

由於您已經繪制到一個單獨的上下文,這里是一個使用圖像掩碼的示例(即 #2):

 let linhas = []; let fundo2; let img; let maskCtx; function setup() { createCanvas(400, 400); pixelDensity(1); fundo2 = createGraphics(400, 400); maskCtx = createGraphics(400, 400); maskCtx.noStroke(); maskCtx.circle(200, 200, 250); img = createImage(width, height); for (let i = 0; i < 100; i++) { let x = random(0, 400); let y = random(0, 400); let z = random(0, 400); let w = random(0, 400); linhas[i] = new Linha(x, y, z, w); } } function draw() { circulo(); tracos(); } function tracos() { for (let linha of linhas) { linha.display(); linha.tremer(); } } function circulo() { img.copy(fundo2, 0, 0, width, height, 0, 0, width, height); img.mask(maskCtx); image(img, 0, 0, width, height); fundo2.noStroke(); fundo2.circle(200, 200, 250); } class Linha { constructor(x, y, z, w) { this.x = x; this.y = y; this.z = z; this.w = w; } display() { fundo2.stroke(255, 0, 0, 70); fundo2.strokeWeight(2); fundo2.line(this.x, this.y, this.z, this.w); } tremer() { this.x = this.x + random(-1, 1); this.y = this.y + random(-1, 1); this.z = this.z + random(-1, 1); this.w = this.w + random(-1, 1); } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM