Figurati, comunque riguardando meglio il codice, si poteva utilizzare larghezza e altezza della canvas stessa.
ps. ora le immagini sono centrate al contenitore canvas.
codice:let ratio = null const selectPhoto = document.getElementById('photo') const c = document.getElementById("tela") const cx = c.getContext("2d") selectPhoto.addEventListener('change', (e) => { const img = new Image() const url = URL.createObjectURL(e.target.files[0]) img.src = url img.onload = () => { (img.width > img.height) ? ratio = img.width / c.width : ratio = img.height / c.height let newWidth = img.width / ratio let newHeight = img.height / ratio const x = (c.width - newWidth) / 2 const y = (c.height - newHeight) / 2 cx.clearRect(0, 0, c.width, c.height) cx.drawImage(img, x, y, newWidth, newHeight) URL.revokeObjectURL(url) } })

Rispondi quotando
