In my Angular 6 application, I’m adding a file upload feature where the uploaded image should be automatically cropped and resized in the preview. I’m using a <canvas>
element and trying to draw the image based on user selection.
Here’s what I have:
<canvas id="canvas"></canvas>
<div style="display:none;">
<img id="source" [src]="url" width="300" height="227">
</div>
<input type='file' (change)="onSelectFile($event)">
And the onSelectFile function:
onSelectFile(event) {
if (event.target.files && event.target.files[0]) {
const reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.onload = (event) => {
this.url = event.target.result;
};
const canvas: any = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const image = document.getElementById('source');
ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);
}
}
Even though I’m referencing examples like this JSFiddle( Edit fiddle - JSFiddle - Code Playground ) , the image doesn’t appear correctly when selected from the file input.
My goal is to allow users to choose a file and immediately preview a cropped and resized version using just plain JavaScript, no jQuery or external libraries.
How can I achieve this with a reliable JavaScript crop image approach that works with the file input and renders the cropped version correctly on the canvas?