In this blog I am going to show you how to take screenshot in javascript and how to pass the screenshot image to backend.
Libraries to take screenshot
html2canvas.js
Step 1: Use below CDN Link
CDN Link: https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.js
Step 2: we need to create a div with ID
<div id="captureDiv">
<div class="owlcodersBlock">
<div class="title">Owlcoders</div>
<div class="links">
<a href="https://owlcoders.com">Owlcoders.com</a>
</div>
<div class="description">Happy Coding :) </div>
</div>
Step 3: Create button to capture the div. In button onClick call a function to take screenshot.
<button onClick=takescreenshot()>Capture Screenshot</button>
Step 4: Create div to show screenshot
<div id="output"></div>
Step 5: Create a function to capture screenshot of captureDiv and append it inside a output div
function takescreenshot() {
let div = document.getElementById('captureDiv');
html2canvas(div).then(
function (canvas) {
document
.getElementById('output')
.appendChild(canvas);
const base64Canvas = canvas.toDataURL();
console.log("base64Canvas", base64Canvas);
})
}
To send captured image to backend
If you want to send the captured image to backend, you can convert screenshot to base64 URL, so that you can easily pass the text to backend by using input or textarea HTML element
To convert screenshot image to base64 URL
const base64Canvas = canvas.toDataURL();
So finally function should be like this
function takescreenshot() {
let div = document.getElementById('captureDiv');
html2canvas(div).then(
function (canvas) {
document
.getElementById('output')
.appendChild(canvas);
const base64Canvas = canvas.toDataURL();
//if you want console and test it
console.log("base64Canvas", base64Canvas);
})
}