I am trying to manipulate images via javascript using canvas.toDataURL('image/webp', 0.8);
but although it works on Android and Windows it does not work on IOS (iPad) which returns a png instead.
Same goes for canvas.toBlob()
I am using Safari 16.6 and Chrome 130.0 on the ipad
https://jsfiddle.net/gdp70xsf/
function doConvert() {
const fileInput = document.querySelector("input[type='file']");
const img = document.querySelector("img");
const canvas = document.querySelector("canvas");
const p = document.querySelector("p");
const ctx = canvas.getContext("2d");
const file = fileInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function (e) {
const imgElement = new Image();
imgElement.src = e.target.result;
imgElement.onload = function() {
// Set up the canvas size
const width = imgElement.width;
const height = imgElement.height;
const dpr = window.devicePixelRatio || 1;
canvas.width = width * dpr;
canvas.height = height * dpr;
// Apply scaling and draw image onto canvas
ctx.scale(dpr, dpr);
ctx.drawImage(imgElement, 0, 0, width, height);
// Convert to WebP and display in the img element
let dataUrl = canvas.toDataURL("image/webp", 0.8);
img.src = dataUrl;
p.innerHTML = navigator.userAgent+'<HR>'+dataUrl.substring(0,30)+'...'; // Logging the base64 string for reference
};
};
reader.readAsDataURL(file);
}
}
</script>
img, canvas {
width:auto;
height:50vh;
vertical-align:top;
}
canvas {
border:solid 1px orange;
}
img {
border:solid 1px red;
}
div {
margin:10px;
}
<input type="file" onChange="doConvert()" />
<div>canvas:<canvas></canvas> img:<img /></div>
<div>
<p></p>
</div>
Is there a way around this (I need to place a canvas
manipulated image back into an <img>
as a webp
on any device type – including the Apple ones)?