Feed webcam sur un canvas js

This commit is contained in:
2023-01-04 22:24:07 +01:00
parent b31ee7c0b9
commit 4bbbe36d28
2 changed files with 65 additions and 45 deletions

View File

@@ -1,12 +1,25 @@
let canvas = document.getElementById('camera'); // Pour l'explication complète du code : https://developer.mozilla.org/en-US/docs/Web/API/Media_Capture_and_Streams_API/Taking_still_photos#javascript
let video = document.getElementById('video'); (() => {
// The width and height of the captured photo. We will set the
// width to the value defined here, but the height will be
// calculated based on the aspect ratio of the input stream.
const width = 320; // We will scale the photo width to this const width = 500; // We will scale the photo width to this
let height = 0; // This will be computed based on the input stream let height = 0; // This will be computed based on the input stream
// |streaming| indicates whether or not we're currently streaming
// video from the camera. Obviously, we start at false.
let streaming = false; let streaming = false;
// The various HTML elements we need to configure or control. These
// will be set by the startup() function.
let video = null;
let canvas = null;
function startup() { function startup() {
video = document.getElementById("video"); video = document.createElement("video");
canvas = document.getElementById("canvas"); canvas = document.getElementById("canvas");
navigator.mediaDevices navigator.mediaDevices
@@ -37,16 +50,23 @@ function startup() {
canvas.setAttribute("width", width); canvas.setAttribute("width", width);
canvas.setAttribute("height", height); canvas.setAttribute("height", height);
streaming = true; streaming = true;
drawVideoOnCanvas();
} }
}, },
false false
); );
} }
window.addEventListener("load", startup, false); function updateCanvas() {
const context = canvas.getContext("2d");
const drawVideoOnCanvas = () => { if (width && height) {
canvas.getContext("2d").drawImage(video, 0, 0, width, height); canvas.width = width;
requestAnimationFrame(drawVideoOnCanvas); canvas.height = height;
context.drawImage(video, 0, 0, width, height);
/* Ajouter Ici le code pour supperposer les animations */
} }
requestAnimationFrame(updateCanvas);
}
window.addEventListener("load", startup, false);
window.addEventListener("load", updateCanvas, false);
})();

View File

@@ -7,7 +7,7 @@
<title>Téléreview</title> <title>Téléreview</title>
</head> </head>
<body> <body>
<canvas id="camera"></canvas> <canvas id="canvas"></canvas>
<video id="video"></video> <script src="assets/js/main.js"></script>
</body> </body>
</html> </html>