Today I want to show you how you can add filters to the video of your web camera or edit the video with the canvas html element
The first thing we need to do is to display the web camera on a video element and then view frame by frame the video element on canvas element.
I already have written an article on how to Display web camera on canvas element , so lets start coding from there.
First lets add a dropdown with the filters available. All filters available for canvas context are here mdn
Add this block of element at index.html:
<div class="dropdown" id="filterselect">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1"
data-bs-toggle="dropdown" aria-expanded="false">
Filter
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li><a class="dropdown-item" value="none">No filter</a></li>
<li><a class="dropdown-item" value="blur(8px)" >Blur</a></li>
<li><a class="dropdown-item" value="contrast(50%)" >Contrast</a></li>
<li><a class="dropdown-item" value="grayscale(100%)" >Grayscale</a></li>
<li><a class="dropdown-item" value="sepia(100%)" >Sepia</a></li>
</ul>
</div>
We wont use all available filters, only blur , sepia , contrast and grayscale.
Next let's add an eventlistener at index.js
var filter=''
filterselect.addEventListener('click', (event) => {
if(event.target.getAttribute('value')){
filter=event.target.getAttribute('value')
}
});
Code explanation:
A filter variable is defined so it is assigned on filter property of context object. Then the value attribute is being assigned on filter variable.
Next step is to apply the filter in context.
Add ctx.filter=filter to drawimage function:
function drawImage(video) {
ctx.drawImage(video, 0, 0, canvaselement.width, canvaselement.height);
ctx.filter = filter
}
We can also add text to our canvas video.
First lets add an input at input.html element so we can dynamically change the text:
<label for="exampleInput" class="form-label">Text</label>
<input class="form-control" id="exampleInput">
<br>
Edit index.js like this:
var canvastext=''
function drawImage(video) {
ctx.drawImage(video, 0, 0, canvaselement.width, canvaselement.height);
ctx.filter = filter
ctx.font = "50px Arial";
ctx.fillText(canvastext, 50, 50);
}
Then add input event listener on input element:
`
var canvastextinput=document.querySelector("#canvastext")
canvastextinput.addEventListener('input',(event=>{
canvastext=event.target.value
}))
The final files are like this:
index.html
index.js
Thanks for your time.
Leave a question or comment below.
Top comments (0)