The code below wants to achieve the following:
<video>
with a live video capture<canvas>
of that video capture<img>
on the page. let video
let canvasSize = 200
let PAUSE_DRAW = false
function setup() {
createCanvas(canvasSize, canvasSize)
video = createCapture(VIDEO)
video.size(canvasSize, canvasSize)
}
async function draw() {
if (video && video.loadedmetadata) {
if (!PAUSE_DRAW) {
// get a 200x200 from the center of the video and draw it on the canvas
image(video.get(), 0, 0, canvasSize, canvasSize, x, y, canvasSize, canvasSize)
let currentFrameAsBase64 = canvas.toDataURL()
// append <img> with current frame as src
document.getElementById('frame').src = currentFrameAsBase64
PAUSE_DRAW = true
}
}
}
Here is the problem I'm having:
The <canvas>
actual size is still 400x400. It's only the image that I draw inside it that's 200x200. As a result, when I get the base64 of the canvas and append it as an <img>
, the img is also 400x400. But I want the <canvas>
and the <img>
to be 200x200 as well.
How do I fix this ?
You have not provided your HTML code, which is necessary. But if I understand you correctly, the video is not the size of the canvas.
The canvas must have its size set in both the styles and attributes, so this is incorrect:
<style>
canvas {
height: 400px;
width: 400px;
}
</style>
<canvas></canvas>
And this is correct:
<style>
canvas {
height: 400px;
width: 400px;
}
</style>
<canvas width="400px" height="400px"></canvas>
Had to change setup() to:
function setup() {
createCanvas(canvasSize, canvasSize)
video = createCapture(VIDEO)
video.size(canvasSize, canvasSize)
video.elt.height = canvasSize
video.elt.width = canvasSize
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.