# 3. The JavaScript
- After the page loads, the script calls the startMedia() function that runs the code that is responsible for taking the video.
- Clicking the button saves the image and displays the stack.
script.js
const videoPlayer = document.querySelector('#player');
const canvasElement = document.querySelector('#canvas');
const captureButton = document.querySelector('#capture-btn');
const imagePicker = document.querySelector('#image-picker');
const imagePickerArea = document.querySelector('#pick-image');
const newImages = document.querySelector('#newImages');
// Image dimensions
const width = 320;
const height = 240;
let zIndex = 1;
const startMedia = () => {
// Play the video if possible
};
// Capture the image, save it and then show it in the page
captureButton.addEventListener('click', (event) => {
});
window.addEventListener("load", (event) => startMedia());
Click to download the source code
The startMedia() function activates the methods that the browser use to take video.
const startMedia = () => {
if (!('mediaDevices' in navigator)) {
navigator.mediaDevices = {};
}
if (!('getUserMedia' in navigator.mediaDevices)) {
navigator.mediaDevices.getUserMedia = (constraints) => {
const getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
if (!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not supported'));
} else {
return new Promise((resolve, reject) => getUserMedia.call(navigator, constraints, resolve, reject));
}
};
}
navigator.mediaDevices.getUserMedia({video: true})
.then((stream) => {
videoPlayer.srcObject = stream;
videoPlayer.style.display = 'block';
})
.catch((err) => {
imagePickerArea.style.display = 'block';
});
};
First, the code checks that the browser has video capturing capabilities which are based on the mediaDevices interface which provides access to connected media devices like cameras and microphones.
If the browser does not support video capturing, the code tries to create the object using the features webkitGetUserMedia or mozGetUserMedia.
If the support exists, the video is displayed. Otherwise, the file upload input field takes command.
Clicking the "Capture" button results in the following:
- Updating the canvas with the picture that the app has just taken.
- Converting the canvas into data that the app can later save as an image file with the following method:
canvasElement.toDataURL()
- And passing the data to the server side with the fetch method.
The data returned from the server includes the location of the image file created and saved by the server.
The script uses the location as the source of the image that it pastes back to the DOM.
// Capture the image, save it and show it in the page
captureButton.addEventListener('click', (event) => {
// Draw the image from the video player on the canvas
canvasElement.style.display = 'block';
const context = canvasElement.getContext('2d');
context.drawImage(videoPlayer, 0, 0, canvas.width, canvas.height);
videoPlayer.srcObject.getVideoTracks().forEach((track) => {
// track.stop();
});
// Convert the data so it can be saved as a file
let picture = canvasElement.toDataURL();
// Save the file by posting it to the server
fetch('/api/save_image.php', {
method : 'post',
body : JSON.stringify({data: picture })
})
.then((res) => res.json())
.then((data) => {
if(data.success){
// Create the image and give it the CSS style with a random tilt
// and a z-index which gets bigger
// each time that an image is added to the div
let newImage = createImage(data.path, "new image", "new image", width, height, "masked");
let tilt = -(20 + 60 * Math.random());
newImage.style.transform = "rotate("+tilt+"deg)";
zIndex++;
newImage.style.zIndex = zIndex;
newImages.appendChild(newImage);
canvasElement.classList.add('masked');
}
})
.catch((error) => console.log(error))
});
- The images that the script stack on the user side are created by the createImage() function:
const createImage = (src, alt, title, width, height, className) => {
let newImg = document.createElement("img");
if(src !== null) newImg.setAttribute("src", src);
if(alt !== null) newImg.setAttribute("alt", alt);
if(title !== null) newImg.setAttribute("title", title);
if(width !== null) newImg.setAttribute("width", width);
if(height !== null) newImg.setAttribute("height", height);
if(className !== null) newImg.setAttribute("class", className);
return newImg;
}