putimagedata 绘制像素数据4次/不按比例

putimagedata drawing pixel data 4 times / not to scale

我最近在 twitch 上观看了 Notch 的一些直播,并对他几年前在 Ludum Dare 挑战赛中使用的一种渲染技术很感兴趣。我尝试将他的 java 代码转换为 java 脚本,但 运行 遇到了一些问题,这是因为我对 ctx.putimagedata 从原始创建的像素值来说还是个新手。

为什么此应用绘制预期输出 4 次,但没有缩放到 window?由于数组的形状,我应该用 4 的乘法或除数迭代的地方有什么我遗漏的吗?我很困惑,所以在这里 post。我发现的唯一解决方法是,如果我将 this.width 和 this.height 调整为乘以 4,但我认为这是在 canvas 的范围之外绘制并导致性能变得糟糕并且不是真正有效的问题解决方案。

class 问题:

document.addEventListener('DOMContentLoaded', () => {
    //setup
    document.body.style.margin = 0;
    document.body.style.overflow = `hidden`;
    const canvas = document.createElement('canvas');
    document.body.appendChild(canvas);
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    const ctx = canvas.getContext("2d");
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    //global helpers
    const randomint = (lower, upper) => {
        return Math.floor((Math.random() * upper+1) + lower);
    }
    const genrandomcolor = () => {
        return [randomint(0, 255), randomint(0, 255), randomint(0, 255), 1/randomint(1, 2)];
    }

    class App {
        constructor(){
            this.scale = 15;
            this.width = window.innerWidth;
            this.height = window.innerHeight;
            this.pixels = [];
            this.fov = 10;
            this.ub = 0;
            this.lr = 0;
            this.keys = {
              up: false,
              down: false,
              left: false,
              right: false
            }
            this.speed = 4;
        }
        update(){
            this.keys.up ? this.ub++ : null;
            this.keys.down ? this.ub-- : null;
            this.keys.left ? this.lr-- : null;
            this.keys.right ? this.lr++ : null;
        }
        draw(){
            this.drawspace()
        }
        drawspace(){
            for(let y = 0; y < this.height; y++){
                let yd = (y - this.height / 2) / this.height;
                yd < 0 ? yd = -yd : null;
                const z = this.fov / yd;
                for (let x = 0; x < this.width; x++){
                    let xd = (x - this.width /2) / this.height * z;
                    const xx = (xd+this.lr*this.speed) & this.scale;
                    const zz = (z+this.ub*this.speed) & this.scale;
                    this.pixels[x+y*this.width] = xx * this.scale | zz * this.scale;
                }
            }
            const screen = ctx.createImageData(this.width, this.height);
            for (let i = 0; i<this.width*this.height*4; i++){
                screen.data[i] = this.pixels[i]
            }
            ctx.putImageData(screen, 0, 0);
        }
    }

    const app = new App;

    window.addEventListener('resize', e => {
        canvas.width = app.width = window.innerWidth;
        canvas.height = app.height = window.innerHeight;
    })
  
    //events
    document.addEventListener("keydown", e => {
        e.keyCode == 37 ? app.keys.left = true : null;
        e.keyCode == 38 ? app.keys.up = true : null;
        e.keyCode == 39 ? app.keys.right = true : null;
        e.keyCode == 40 ? app.keys.down = true : null;
    })
    document.addEventListener("keyup", e => {
        e.keyCode == 37 ? app.keys.left = false : null;
        e.keyCode == 38 ? app.keys.up = false : null;
        e.keyCode == 39 ? app.keys.right = false : null;
        e.keyCode == 40 ? app.keys.down = false : null;
    })

    //game loop
    const fps = 60;
    const interval = 1000 / fps;
    let then = Date.now();
    let now;
    let delta;
    const animate = time => {
        window.requestAnimationFrame(animate);
        now = Date.now();
        delta = now - then;
        if (delta > interval) {
            then = now - (delta % interval)
            ctx.fillStyle = 'black';
            ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
            app.update();
            app.draw();
        }
    }
    animate();
});

ImageData.data 对象是一个 Uint8ClampedArray,表示每个像素的 4 个红色、绿色、蓝色和 Alpha 通道,每个通道表示为 8 位(值在 0-255 范围内)。

这意味着要设置一个像素,需要独立设置它的4个通道:

const r = data[0];
const g = data[1];
const b = data[2];
const a = data[3];

这代表我们 ImageData 的第一个像素(左上角的像素)。
因此,为了能够遍历所有像素,我们需要创建一个循环,使我们能够从一个像素转到另一个像素。这是通过一次迭代 4 个索引来完成的:

for(
   let index = 0;
   index < data.length;
   index += 4 // increment by 4
) {
  const r = data[index + 0];
  const g = data[index + 1];
  const b = data[index + 2];
  const a = data[index + 3];
  ...
}

现在每个像素都将按需要遍历:

  //setup
  document.body.style.margin = 0;
  document.body.style.overflow = `hidden`;
  const canvas = document.createElement('canvas');
  document.body.appendChild(canvas);
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  const ctx = canvas.getContext("2d");
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  //global helpers
  const randomint = (lower, upper) => {
    return Math.floor((Math.random() * upper + 1) + lower);
  }
  const genrandomcolor = () => {
    return [randomint(0, 255), randomint(0, 255), randomint(0, 255), 1 / randomint(1, 2)];
  }

  class App {
    constructor() {
      this.scale = 15;
      this.width = window.innerWidth;
      this.height = window.innerHeight;
      this.pixels = [];
      this.fov = 10;
      this.ub = 0;
      this.lr = 0;
      this.keys = {
        up: false,
        down: false,
        left: false,
        right: false
      }
      this.speed = 4;
    }
    update() {
      this.keys.up ? this.ub++ : null;
      this.keys.down ? this.ub-- : null;
      this.keys.left ? this.lr-- : null;
      this.keys.right ? this.lr++ : null;
    }
    draw() {
      this.drawspace()
    }
    drawspace() {
      for (let y = 0; y < this.height; y++) {
        let yd = (y - this.height / 2) / this.height;
        yd < 0 ? yd = -yd : null;
        const z = this.fov / yd;
        for (let x = 0; x < this.width; x++) {
          let xd = (x - this.width / 2) / this.height * z;
          const xx = (xd + this.lr * this.speed) & this.scale;
          const zz = (z + this.ub * this.speed) & this.scale;
          this.pixels[x + y * this.width] = xx * this.scale | zz * this.scale;
        }
      }
      const screen = ctx.createImageData(this.width, this.height);
      for (let i = 0, j=0; i < screen.data.length; i += 4) {
        j++; // so we can iterate through this.pixels
        screen.data[i] = this.pixels[j]; // r
        screen.data[i + 1] = this.pixels[j], // g
        screen.data[i + 2] = this.pixels[j] // b
        screen.data[i + 3] = 255; // full opacity
      }
      ctx.putImageData(screen, 0, 0);
    }
  }

  const app = new App;

  window.addEventListener('resize', e => {
    canvas.width = app.width = window.innerWidth;
    canvas.height = app.height = window.innerHeight;
  })

  //events
  document.addEventListener("keydown", e => {
    e.keyCode == 37 ? app.keys.left = true : null;
    e.keyCode == 38 ? app.keys.up = true : null;
    e.keyCode == 39 ? app.keys.right = true : null;
    e.keyCode == 40 ? app.keys.down = true : null;
  })
  document.addEventListener("keyup", e => {
    e.keyCode == 37 ? app.keys.left = false : null;
    e.keyCode == 38 ? app.keys.up = false : null;
    e.keyCode == 39 ? app.keys.right = false : null;
    e.keyCode == 40 ? app.keys.down = false : null;
  })

  //game loop
  const fps = 60;
  const interval = 1000 / fps;
  let then = Date.now();
  let now;
  let delta;
  const animate = time => {
    window.requestAnimationFrame(animate);
    now = Date.now();
    delta = now - then;
    if (delta > interval) {
      then = now - (delta % interval)
      ctx.fillStyle = 'black';
      ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
      app.update();
      app.draw();
    }
  }
  animate();

但请注意,您还可以在 ArrayBuffer 上使用其他视图,并直接将每个像素作为 32 位值处理:

//setup
  document.body.style.margin = 0;
  document.body.style.overflow = `hidden`;
  const canvas = document.createElement('canvas');
  document.body.appendChild(canvas);
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  const ctx = canvas.getContext("2d");
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  //global helpers
  const randomint = (lower, upper) => {
    return Math.floor((Math.random() * upper + 1) + lower);
  }
  const genrandomcolor = () => {
    return [randomint(0, 255), randomint(0, 255), randomint(0, 255), 1 / randomint(1, 2)];
  }

  class App {
    constructor() {
      this.scale = 15;
      this.width = window.innerWidth;
      this.height = window.innerHeight;
      this.pixels = [];
      this.fov = 10;
      this.ub = 0;
      this.lr = 0;
      this.keys = {
        up: false,
        down: false,
        left: false,
        right: false
      }
      this.speed = 4;
    }
    update() {
      this.keys.up ? this.ub++ : null;
      this.keys.down ? this.ub-- : null;
      this.keys.left ? this.lr-- : null;
      this.keys.right ? this.lr++ : null;
    }
    draw() {
      this.drawspace()
    }
    drawspace() {
      for (let y = 0; y < this.height; y++) {
        let yd = (y - this.height / 2) / this.height;
        yd < 0 ? yd = -yd : null;
        const z = this.fov / yd;
        for (let x = 0; x < this.width; x++) {
          let xd = (x - this.width / 2) / this.height * z;
          const xx = (xd + this.lr * this.speed) & this.scale;
          const zz = (z + this.ub * this.speed) & this.scale;
          this.pixels[x + y * this.width] = xx * this.scale | zz * this.scale;
        }
      }
      const screen = ctx.createImageData(this.width, this.height);
      // use a 32bits view
      const data = new Uint32Array(screen.data.buffer);
      for (let i = 0, j=0; i < this.width * this.height; i ++) {
        // values are 0-255 range, we convert this to 0xFFnnnnnn 32bits
        data[i] = (this.pixels[i] / 255 * 0xFFFFFF) + 0xFF000000;
      }
      ctx.putImageData(screen, 0, 0);
    }
  }

  const app = new App;

  window.addEventListener('resize', e => {
    canvas.width = app.width = window.innerWidth;
    canvas.height = app.height = window.innerHeight;
  })

  //events
  document.addEventListener("keydown", e => {
    e.keyCode == 37 ? app.keys.left = true : null;
    e.keyCode == 38 ? app.keys.up = true : null;
    e.keyCode == 39 ? app.keys.right = true : null;
    e.keyCode == 40 ? app.keys.down = true : null;
  })
  document.addEventListener("keyup", e => {
    e.keyCode == 37 ? app.keys.left = false : null;
    e.keyCode == 38 ? app.keys.up = false : null;
    e.keyCode == 39 ? app.keys.right = false : null;
    e.keyCode == 40 ? app.keys.down = false : null;
  })

  //game loop
  const fps = 60;
  const interval = 1000 / fps;
  let then = Date.now();
  let now;
  let delta;
  const animate = time => {
    window.requestAnimationFrame(animate);
    now = Date.now();
    delta = now - then;
    if (delta > interval) {
      then = now - (delta % interval)
      ctx.fillStyle = 'black';
      ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
      app.update();
      app.draw();
    }
  }
  animate();