Learn to capture webcam streams and integrate ML models using JavaScript with our easy, step-by-step guide for innovative web apps!

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
// Select video element from your HTML
const videoElement = document.getElementById('webcam');
// Request access to the webcam
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
// Set the source of the video element to the webcam stream
videoElement.srcObject = stream;
videoElement.play();
})
.catch(error => {
// Handle error in case the user denies webcam access
console.error('Error accessing webcam:', error);
});
// Create a canvas element in your HTML or dynamically via JavaScript
const canvasElement = document.getElementById('captureCanvas');
const canvasContext = canvasElement.getContext('2d');
// Function to capture the current frame from the video
function captureFrame() {
// Draw the video frame on the canvas; width and height should match your video or canvas size
canvasContext.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
// Get image data from the canvas
const imageData = canvasContext.getImageData(0, 0, canvasElement.width, canvasElement.height);
return imageData;
}
// Load a pre-trained model hosted online or locally.
// For example, replace 'model.json' with the path or URL to your model.
async function loadModel() {
const model = await tf.loadLayersModel('model.json');
return model;
}
// Load the model at startup
let mlModel;
loadModel().then(loadedModel => {
mlModel = loadedModel;
console.log('ML model loaded successfully');
});
// Example function to preprocess image data from canvas for model prediction
function preprocessImage(imageData) {
// Convert the image data into a tensor
let tensor = tf.browser.fromPixels(imageData);
// Resize the image to the required input shape of the model, for instance 224x224 pixels
tensor = tf.image.resizeBilinear(tensor, [224, 224]);
// Normalize the image values from [0, 255] to [0, 1]
tensor = tensor.toFloat().div(tf.scalar(255));
// Expand dimensions to match the model input if necessary (e.g., [1, 224, 224, 3])
tensor = tensor.expandDims();
return tensor;
}
async function predictFrame() {
// Capture the current frame from the video
const imageData = captureFrame();
// Preprocess the captured image data
const inputTensor = preprocessImage(imageData);
// Obtain predictions from the ML model
const predictions = await mlModel.predict(inputTensor);
// Process the output predictions (e.g., convert logits to probabilities or extract labels)
console.log('Predictions:', predictions);
// Dispose tensor to free memory
inputTensor.dispose();
}
function processVideoStream() {
// Continuously capture frames and run prediction
predictFrame();
// Use requestAnimationFrame for a smooth loop execution
requestAnimationFrame(processVideoStream);
}
// Start the continuous prediction loop after the model has loaded
loadModel().then(() => {
processVideoStream();
});
// Assume you have an element in your HTML with the ID 'resultDisplay'
const resultDisplay = document.getElementById('resultDisplay');
async function predictFrameAndDisplay() {
const imageData = captureFrame();
const inputTensor = preprocessImage(imageData);
const predictions = await mlModel.predict(inputTensor);
// Format the predictions for display
// Here, you might convert a tensor to an array, find the highest probability, etc.
predictions.array().then(predictionArray => {
resultDisplay.innerText = 'Predictions: ' + JSON.stringify(predictionArray);
});
inputTensor.dispose();
requestAnimationFrame(predictFrameAndDisplay);
}
// Begin the loop once the model is loaded
loadModel().then(() => {
predictFrameAndDisplay();
});
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.