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

Time:11-09

With the code below I want to end up with:

  1. a 400x400 camera capture
  2. a 400x400 canvas
  3. a 400x400 image
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()

}

Instead, what I end up with is:

  1. a 400x400 camera capture
  2. a 400x400 canvas with its width and height attributes set to 800
  3. a 800x800 image

How do I fix this ?

You can see the problem in action here

CodePudding user response:

The canvas's width and height properties are set to 800 because you are running this sketch on a high DPI (i.e. Apple Retina) display. When p5.js detects this it sets pixel density to 2 by default so it's taking 800 pixel square of graphics and squishing it into a 400 "pixel" square on the screen. If you want an image that is exactly 400 actual pixels, you could set pixel density to 1 in your setup() function: pixelDensity(1).

  • Related