context.arc(x,y,r,S角度,E角度,逆时针);我可以在画布上做z方向的移动吗

context.arc(x,y,r,sAngle,eAngle,counterclockwise); can i make this move in the z direction also in canvas?

本文关键字:角度 移动 方向 我可以 arc context 逆时针      更新时间:2023-09-26

我有一些随机粒子。我想把它们放在三维空间里。到目前为止,我只能在2d中放置它们。如何在3d中定位它们?

Canvas 2D上下文(其中arc()可用)根据定义仅为2D。若要使用三维,您需要使用WebGL,或者手动将三维坐标投影到二维画布上。

在后两个选项中,arc()也不可用,因此需要使用多段线/多边形手动定义圆弧。

在2D画布上进行3D投影的示例

大量未优化但经过简化以显示基本功能。

// Lets make a basic and simple 3D Point class
 function Point3D(x, y, z) {
   this.x = x;
   this.y = y;
   this.z = z;
   //rotated coords after using rotation
   this.rx = x;
   this.ry = y;
   this.rz = z;
}
Point3D.prototype = {
  rotateX: function(angle) {
    var rd, ca, sa;
    ca = Math.cos(angle);
    sa = Math.sin(angle);
    this.ry = this.y * ca + this.z * sa;
    this.rz = this.y * sa - this.z * ca;
    return new Point3D(this.rx, this.ry, this.rz)
  },
  
  rotateY: function(angle) {
    var rd, ca, sa;
    ca = Math.cos(angle);
    sa = Math.sin(angle);
    this.rz = this.z * ca - this.x * sa;
    this.rx = this.z * sa + this.x * ca;
    return new Point3D(this.rx, this.ry, this.rz)
  },
  
  rotateZ: function(angle) {
    var rd, ca, sa;
    ca = Math.cos(angle);
    sa = Math.sin(angle);
    this.rx = this.x * ca + this.y * sa;
    this.ry = this.x * sa - this.y * ca;
    return new Point3D(this.rx, this.ry, this.rz)
  },
  project: function(w, h, fov, viewDist) {
    var f, x, y;
    f = fov / (viewDist + this.rz);
    x = this.rx * f + w * 0.5;
    y = this.ry * f + h * 0.5;
    return new Point3D(x, y, this.rz)
  }
}
// create an arc using 3D points
var arc = [];
for(var a = 0; a < Math.PI; a += 0.1) {
  arc.push(new Point3D(Math.cos(a) * 0.8, Math.sin(a) * 0.8, 0))
}
// animate
var ctx = c.getContext("2d");
ctx.lineWidth = 3;
a = 0;
(function loop() {
  ctx.clearRect(0, 0, c.width, c.height);
  ctx.beginPath();
  for(var i = 0, p; p = arc[i++];) {
    // some random rotation and projection (play with the parameters)
    p = p.rotateZ(a*0.1).rotateY(a).rotateX(-a*0.05).project(c.width, c.height, 600, 7);
    i === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y);
  }
  ctx.stroke();
  
  a += 0.05;
  requestAnimationFrame(loop)
})();
<canvas id=c></canvas>