📌demo
const encodeBase64 = (file) => {
const reader = new FileReader();
reader.readAsDataURL(file);
return new Promise((resolve) => {
reader.onload = () => {
resolve(reader.result);
};
});
};
const $upload = document.getElementById("uploadFile");
$upload.addEventListener("change", async (e) => {
await upload(e.target.files[0]);
});
async function upload(file){
const imgDataURL = await encodeBase64(file);
}
async function upload(file) {
const imgDataURL = await encodeBase64(file);
const image = new Image();
image.src = imgDataURL;
image.onload = () => {
const width = image.width;
const height = image.height;
const ratio = height / width;
resultCanvas.drawImage(image, { width, height, ratio });
};
}
canvas class {
.....
drawImage(img, imgSize) {
const { width: imgWidth, height: imgHeight, ratio } = imgSize;
const canvasWidth = this.$canvas.width;
const canvasHeight = this.$canvas.height;
const width = canvasWidth;
const height = canvasWidth * ratio;
this.ctx.drawImage(img, 0, 0, width, height);
}
class Canvas {
...
setEvent() {
const that = this;
this.$canvas.addEventListener("mousemove", (e) => {
const { offsetX, offsetY } = e;
that.drawLine(offsetX, offsetY);
});
this.$canvas.addEventListener(
"mousedown",
this.startDrawing.bind(this)
);
this.$canvas.addEventListener("mouseup", this.endDrawing.bind(this));
}
drawLine(x, y) {
if (!this.isDrawing) return;
this.ctx.beginPath();
this.ctx.arc(x, y, 10, 0, Math.PI * 2);
this.ctx.closePath();
this.ctx.fill();
}
}
const $download = document.getElementById("download");
function download() {
const image = resultCanvas
.getDataURL()
.replace("image/png", "image/octet-stream");
$download.setAttribute("href", image);
$download.setAttribute("download", "helloWorld.png");
}
$download.addEventListener(
"click",
(e) => (e.target.href = resultCanvas.getDataURL())
);