I got this small example where I am adding images to the DOM. I tried to create a function for clearing the element to where I am adding the images by:
document.querySelector("#photo2").innerHTML = "";
but it didnt work as I expected.
How can I clear the element without reloading the page?
Here is my codepen: ' https://codepen.io/haangglide/pen/VwjqmZp
Updated code with more comments in the code, i tried to make it more compact as well
I think basically my problem is that Im creating new Image elements for each snapshot where i place the generated imageuri. I started creating multiple canvases but pretty soon it got very heavy.
HTML
<button id="btn" disabled>take a snapshot</button>
<button id="btn-remove">remove all the images</button>
<video></video>
<canvas id="photo2"></canvas>
And my javascript
const vid = document.querySelector('video');
let images = [];
navigator.mediaDevices.getUserMedia({video: true }) // request cam
.then(stream => {
vid.srcObject = stream;
return vid.play(); // returns a Promise
})
.then(()=>{ // enable the button
const btn = document.querySelector('#btn');
btn.disabled = false;
btn.onclick = e => {
train0Snap()
};
const btnremove = document.querySelector('#btn-remove');
btnremove.disabled = false;
btnremove.onclick = e => {
clearAllImages();
};
});
function clearAllImages() {
document.querySelector("#photo2").innerHTML = "";
}
function train0Snap(){
// set random position
let x = Math.floor(Math.random() * 20);
let y = Math.floor(Math.random() * 20);
let angleInRadians = (Math.random() * 0.2) - 0.1;
// 1) CREATING A CANVAS FOR DOING THE TRANSFORMATIONS IN
const newCanvas = document.createElement('canvas');
// Set width and height of thumb based on the video
newCanvas.width = vid.videoWidth * 0.3;
newCanvas.height = vid.videoHeight * 0.3;
// getting canvas 2D rendering context pf the created canvas
const ctx = newCanvas.getContext('2d');
// centrate thumbsize
var xx = newCanvas.width / 2;
var yy = newCanvas.height / 2;
// create rotationmatrix
ctx.translate(xx, yy);
ctx.rotate(angleInRadians);
// 2) DRAW THE VIDEO IN THE CONTEXT BASED ON THE NEW SIZE
ctx.drawImage(vid, -newCanvas.width /2 , -newCanvas.height /2, newCanvas.width/2, newCanvas.height/2);
// 3) GET THE CANVAS ELEMENT FROM THE DOM FOR DRAWING EVERYTHING
var canvas2 = document.getElementById('photo2');
// creating a rendering context for the output
var ctxoutput = canvas2.getContext('2d');
// creating a new Image element for each image and put it in the context
var image2 = new Image();
image2.onload = function() {
ctxoutput.drawImage(image2, 20, 0);
};
// returns a data URI containing a representation of the image
var canvasToUrl = newCanvas.toDataURL();
// 4) SET THE IMAGESOURCE OF THE NEW IMAGE ELEMENT
image2.src = canvasToUrl;
}
SOLUTION
function clearAllImages() {
var canvas2 = document.getElementById('photo2');
const context = canvas2.getContext('2d');
context.clearRect(0, 0, canvas2.width, canvas2.height);
}