首页 > 解决方案 > 2D Canvas 上 createGraphics WEBGL 中的 orbitControl

问题描述

我无法让 orbitControl() 在 2d P5.js 画布内的 createGraphics WEBGL 函数中工作。

// draw a sphere with radius 40
function setup() {
  createCanvas(100, 100);
    pg = createGraphics(100, 100, WEBGL);
}

function draw() {
  background(205, 102, 94);
  pg.sphere(40);
  pg.orbitControl();
  image(pg,0,0)
}

有人可以帮忙吗?

标签: javascriptp5.js

解决方案


orbitControl函数无法在p5.Graphics创建时使用,createGraphics因为它们不接收/处理输入事件,只有主草图实例可以。但是,您可以自己实现轨道控制功能:

const sensitivityX = 2;
const sensitivityY = 1;
const sensitivityZ = 0.1;
const scaleFactor = 100;

let pg;
let cam;

// draw a sphere with radius 40
function setup() {
  createCanvas(100, 100);
  pg = createGraphics(100, 100, WEBGL);
  cam = pg.createCamera();
}

function draw() {
  background(205, 102, 94);
  pg.clear();
  pg.sphere(40);
  image(pg, 0, 0);
}

function mouseDragged() {
  // I'm only implementing orbit and zoom here, but you could implement
  // panning as well.
  
  // Technically _orbit is not a publicly documented part of the
  // p5.Camera API. I will leave it as an excersise to the reader to
  // re-implement this functionality via the public API.
  
  // The _orbit function updates the Euler angles for the position of
  // the camera around the target towards which it is oriented, and
  // adjusts its distance from the target.
  const deltaTheta =
    (-sensitivityX * (mouseX - pmouseX)) / scaleFactor;
  const deltaPhi =
    (sensitivityY * (mouseY - pmouseY)) / scaleFactor;
  cam._orbit(deltaTheta, deltaPhi, 0);
}

function mouseWheel(event) {
  if (event.delta > 0) {
    cam._orbit(0, 0, sensitivityZ * scaleFactor);
  } else {
    cam._orbit(0, 0, -sensitivityZ * scaleFactor);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>


推荐阅读