The code I have below will take an uploaded image and center it on a canvas, it is working but I'm unable to change the size of the actual image. I want to be able to upload an image and then scale it down by a percentage or pixel with it centered.
The way it works right now is you upload an image and it automatically gets populated on the canvas. The final product will return a base64 string that I will convert using C#.
Any help would be great, thanks.
HTML:
<input type="file">
Javascript:
$("input").on("change", function(e) {
var file = this.files[0];
if (!file) return;
var fileReader = new FileReader();
fileReader.onload = () => {
var image = new Image();
image.onload = () => {
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
// Change Background
context.beginPath();
context.rect(0, 0, 1000, 1000);
context.fillStyle = "#7D8491";
context.fill();
// Draw Logo
context.drawImage(image, canvas.width / 2 - image.width / 2,
canvas.height / 2 - image.height / 2);
// Append to body
$("body").append(canvas);
// Open base64 url
//window.open(canvas.toDataURL("image/png"));
};
image.src = fileReader.result;
};
fileReader.readAsDataURL(file);
var canvas = document.createElement("canvas");
});
I simply had to divide both the position and the actual width/height by the percentage I wanted to scale the image down.
// Draw Logo
context.drawImage(
image,
canvas.width / 2 - image.width * .75 / 2,
canvas.height / 2 - image.height * .75 / 2,
image.width * .75, image.height * .75
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.