I use the html2canvas library to capture screenshots by passing in a className and saving the image file as a blob. However, when the image is saved or downloaded, there is an issue with elements that have background-image: url(data:image/svg+xml;base64,...)
(SVG image), but PNG images are not affected. I am using html2canvas version 1.4.1.
function captureImg(className) {
const bannerElement = document.querySelector('.' + className);
return html2canvas(bannerElement, {
scale: 2,
backgroundColor: null,
}).then(canvas => {
return new Promise((resolve, reject) => {
canvas.toBlob(blob => {
if (blob) {
const file = new File([blob], 'banner-screenshot.png', {
type: 'image/png'
});
resolve(file);
} else {
reject(new Error('Failed to convert canvas to blob'));
}
}, 'image/png');
});
}).finally(() => {
}).catch(error => {
console.error('Error capturing the banner:', error);
});
}
function captureImgNow() {
captureImg('basic-box').then(file => {
const formData = new FormData();
formData.append('file_img', file);
formData.append('error_now', error_now);
formData.append('user_learn_id', user_learn_id);
formData.append('lesson_id', lesson_id);
formData.append('detail_id', detail_id);
formData.append('type', 'wrong');
formData.append('max_error', max_error);
$.ajax({
url: '/save-user-note-exam-failed',
method: 'POST',
contentType: 'application/json',
data: formData,
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log('captureImgNow');
},
error: function (xhr) {
}
});
})
}
This is the image I want
This is result
This this CSS
I tried dom-to-image, but the speed is quite slow and not suitable for my project.
<img width="200px" height="200px" style="z-index: 1000; position: absolute; top: 50%; left: 50%;" src="<%= item.image_background_gray == null ? item.image_background : item.image_background_gray%>" alt="test">
This is an image test
This is the result test
2
Answers
You can try writing this code
You can try adding
const svgData =
data:image/svg+xml;base64,${window.btoa(unescape(encodeURIComponent(new XMLSerializer().serializeToString(svgElement))))}
;