This is my source code. I use the dom-to-image plugin to capture images for downloading or sharing. The download functionality works well in all environments. However, the Web Share API works perfectly on Android browsers, such as Chrome and Brave. On iOS browsers, like Safari and even Chrome, the image is incorrect on the first click, and you need to click twice to get the correct result, how to fix it on iOS.
function shareImage(id) {
const content = document.getElementById(id);
try {
domtoimage.toBlob(content).then(blob => {
const file = new File([blob], 'share.jpg', {
type: 'image/jpeg'
});
if (navigator.share) {
navigator.share({
title: 'share test',
files: [file]
})
.then(() => console.log('Successful share'))
.catch((error) => console.error('Error sharing', error));
} else {
alert('not support');
}
});
} catch (error) {
console.error('convert error', error);
}
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('btn_download').addEventListener('click', function() {
domtoimage.toJpeg(document.getElementById('capture'), {
quality: 0.95
})
.then(function(dataUrl) {
const link = document.createElement('a');
link.download = 'download.jpg';
link.href = dataUrl;
link.click();
});
return false;
});
document.getElementById('btn_share').addEventListener('click', shareImage.bind(null, 'capture'));
});
.canvas {
background: #000;
position: relative;
transform: rotate(3deg);
height: 400px;
width: 400px;
}
.canvas img {
max-width: 400px;
}
.canvas div {
position: absolute
}
.el-p {
filter: grayscale(100%);
}
.el-f {
opacity: .5
}
.el-t {
color: #fff;
left: 28%;
top: 70%;
transform: skew(10deg, 0deg) rotate(10deg);
font-size: 40px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css">
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<div class="canvas" id="capture">
<div class="el-p"><img src="https://picsum.photos/id/1/500/300" alt=""></div>
<div class="el-f"><img src="https://i.imgur.com/bCgZZWA.png" alt=""></div>
<div class="el-t">Nice!!!!!</div>
</div>
<div class="col-md-12 text-center mt-5">
<button type="button" id="btn_download">download</button>
<button type="button" id="btn_share">share</button>
</div>
</div>
</div>
</div>