codice:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<style>
#canvas {
width: 300px;
height: 300px;
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<br>
<label for="photo">Canvas</label>
<input type="file" name="photo" accept="image/*" id="photo">
<script>
const selectPhoto = document.getElementById('photo')
const canvas = document.getElementById("canvas")
const cx = canvas.getContext("2d")
cx.width = 300
cx.height = 300
selectPhoto.addEventListener('change', (e) => {
const img = new Image()
const url = URL.createObjectURL(e.target.files[0])
img.src = url
img.onload = () => {
let imageWidth = img.width
let imageHeight = img.height
let cWidth = cx.width
let cHeight = cx.height
let ratio = Math.min((cx.width / img.width), (cx.height / img.height))
let newWidth = img.width * ratio
let newHeight = newWidth / 2
cx.clearRect(0, 0, cx.width, cx.height)
cx.drawImage(img, 0, 0, img.width, img.height, 0, 0, newWidth, newHeight)
URL.revokeObjectURL(url)
}
})
</script>
</body>
</html>