I want to upload an Img to a HTML-Canvas and want to see it immediately after uploading finished. How can I maintain the proper aspect ratio for the images?
Huge images have to be resized to a given canvas size because they shouldn't be allowed to fill the entire viewport.
Small images should get a resizing, too, to fill the canvas.
Only making use of HTML + CSS + vanilla JS
What I did so far:
var fileUpload = document.getElementById('fileUpload');
var canvas = document.getElementById("renderCanvas");
var ctx = canvas.getContext("2d");
var img = new Image()
function scaleImage() {
const windowWidth = window.screen.width
const windowHeight = window.screen.height
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
var scaledWidth, scaledHeight;
if(img.width > img.height){
scaledWidth = ctx.canvas.width;
scaledHeight = (ctx.canvas.width / img.width) * img.height
}else if(img.width < img.height){
scaledWidth = (ctx.canvas.height / img.height) * img.width
scaledHeight = ctx.canvas.height;
}else{
scaledWidth = ctx.canvas.width;
scaledHeight = ctx.canvas.height;
}
ctx.drawImage(
img,
(ctx.canvas.width / 2) - (scaledWidth / 2),
(ctx.canvas.height / 2) - (scaledHeight / 2),
scaledWidth,
scaledHeight
);
};
// readImage ersetzt das Bild
function readImage() {
if ( this.files && this.files[0] ) {
var fileReader = new FileReader();
fileReader.onload = function(e) {
this.img = img
this.img.src = e.target.result;
img.onload = scaleImage
};
fileReader.readAsDataURL( this.files[0] );
}
}
fileUpload.onchange = readImage;
window.onresize = scaleImage;
I can upload an Img-File and display it. It's not really fitting the canvas size and if I resize my browser window it keeps resizing and getting bigger beyond the borders of my canvas.
If you want a max size for an image after uploading, you can use the css max-width attribute. if this image is in a div you can add a width to the div and make the image max-width - auto or 100%
the code would be something like this
.width-100{
width: 100px;
}
.100{
max-width:100%
}
<div class="width-100">
<img class="100" src="example" alt="example">
</div>