p5.js 3D 草图中的背景图像

Background image in p5.js 3D sketch

我有一个 p5.js 3D 草图。我必须设置它的背景图片。我知道我们可以在 2D 草图中使用相同的 background() 函数轻松实现它,但在 3D 草图中是不可能的。

我在谷歌上搜索了一些技巧,发现我可以有一个 plane,其背面的尺寸为 canvas,然后使用 texture() 设置其背景图像,例如下面的例子。

var img;
function preload() {
  img = loadImage("img.png");
}

function setup() { 
  createCanvas(600, 600, WEBGL);
} 

function draw() { 
  background(220);
  
  push();
  texture(img);
  plane(600, 600);
  pop();
}

但问题是 - 我必须在草图中使用 orbitControl()。因此,当我四处拖动时,背景 (plane) 也会移动。我希望我的背景是静态的(当我移动其他物体时它不应该移动)。

最后,我使出css background-image 属性设置canvas的背景图,去掉draw()中的background(255) ] 功能。但是由于这个原因,当我拖动对象时,背景(前几帧)没有重叠并且也可见。

在这种情况下如何实现背景图片?

我的素描可以在 https://editor.p5js.org/praneetdixit1234/sketches/9pN4lA8KB

找到

我认为你的 CSS 方法很好,只是不确定为什么在大小上使用 cover ...
你的图片是1365px宽但是你的canvas只有600px,有cover大部分会被隐藏,文字不会完全看清,但是以后如果你换图片用cover可能没事。

这是我用的

canvas {
  display: block;
  background-image: url("https://static.vecteezy.com/system/resources/previews/000/118/983/original/free-vector-cityscape.jpg");
  background-size: contain;
  background-repeat: no-repeat;
}

...并且不要删除背景,设置 alpha background(0,0,0,0);
这是工作示例:
https://editor.p5js.org/heldersepu/sketches/ll8txfcs0


我还在样本中添加了 smooth()

差异很明显,请在此处阅读更多信息:
https://p5js.org/reference/#/p5/smooth

您应该将背景和 3d 对象渲染到不同的图像表面,然后将它们组合到 canvas。

举个例子: https://editor.p5js.org/space-haze/sketches/alWGuuXXe

var w = window.innerWidth;
var h = window.innerHeight;
function setup() {

  // create the primary drawing surface
  createCanvas(w, h);
  
  // create a 3d off-screen surface
  img3d = createGraphics(w,h,WEBGL);       
  
}

function draw() {
  // draw our background color/image to canvas
  background(color('purple'));
  
  // render our 3d objects to off-screen surface
  let x = w/3;
  img3d.fill(color('yellow'));
  img3d.stroke(color('black'));
  img3d.strokeWeight(2);
  img3d.camera(x*2,x*2,x*2,0,0,0,0,1,0);
  img3d.box(x);

  // draw our off-screen surface to canvas
  image(img3d,0,0);
}