p5.js |如何将 canvas 的大小设置为捕获的大小

p5.js | How do I set the size of the canvas to that of the capture

我想用下面的代码结束:

  1. 400x400 相机拍摄
  2. 400x400 canvas
  3. 400x400 图片
let capture
let universalWidth = 400
let testImg = undefined

function setup() {
  testImg = document.getElementById('test')
  
  capture = createCapture({
    audio: false,
    video: {
      width: universalWidth,
      height: universalWidth
    }
  })

  capture.size(universalWidth, universalWidth)

  createCanvas(universalWidth, universalWidth)
}

function draw() {

  image(capture.get(), 0, 0)

  testImg.src = canvas.toDataURL()

}

相反,我最终得到的是:

  1. 400x400 相机拍摄
  2. a 400x400 canvas 其 widthheight 属性设置为 800
  3. 一张 800x800 的图片

我该如何解决这个问题?

您可以在实际操作中看到问题 here

canvas 的宽度和高度属性设置为 800,因为您 运行 此草图是在高 DPI(即 Apple Retina)显示器上显示的。当 p5.js 检测到它时,默认情况下它会将像素密度设置为 2,因此它会将 800 像素的正方形图形压缩成屏幕上 400“像素”的正方形。如果您想要一张正好有 400 个实际像素的图像,您可以在 setup() 函数中将像素密度设置为 1pixelDensity(1).