Home > database >  how to set min-width, max-width, min-height, max-height for canvas element
how to set min-width, max-width, min-height, max-height for canvas element

Time:07-19

function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        canvas.width = 1920;
        canvas.height = 1080;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        var dataURL = canvas.toDataURL("image/jpg");
        return dataURL.replace(/^data:image\/(jpg);base64,/, "");
}

I am uploading this image, but I want to make sure that if the pixels of the uploading image is less than 480p, it will draw a 480p image on canvas before upload and if the pixels of the uploading image is greater than 1080p, it will draw a 1080p image on canvas before upload.

So basically my question is, is there any way to set min-height, max-height, min-width, and max-width on canvas or any other alternative through which I can change the resolution of the image before uploading.

CodePudding user response:

You can do the below, please note a very quick answer you may want to improve the code:

 function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    let image = document.createElement("img");
    image.setAttribute("src", img);

    setTimeout(function(){
        if(image.height == 1080){
            canvas.width = 1920;
            canvas.height = 1080;
        }
        if(image.height == 480){
            canvas.width = 640;
            canvas.height = 480;
        }
    },0)

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    var dataURL = canvas.toDataURL("image/jpg");
    return dataURL.replace(/^data:image\/(jpg);base64,/, "");
}

CodePudding user response:

You can edit this in css by using a class called "canvas" and put the min-width, max-width that you want there:

.canvas{
    min-width: //whatever you want;
    max-width: //whatever you want;
}

Then in the javascript function you can change the class name of your canvas:

canvas.className = "canvas";

Hopefully this helps you.

  • Related