Question

I am able to upload an image to the browser and convert it to a BLOB. After that I attempt to draw it into my canvas but it's not being recognized. I have a feeling it is something small that I am missing but I can not see it. Any help would be awesome!

var resize_img  = 
function(){

    var file = document.getElementById("add_img").files;

    // add in file type checker

    // Create img element to PREVIEW
    var img = document.createElement("img");
    img.src = window.URL.createObjectURL(file[0]);


    // Draw image to CANVAS
    var canvas_e = document.getElementById("canvas_img");
    var ctx = canvas_e.getContext("2d");
    ctx.drawImage(img, 0, 0);

    //Resize Image
    var MAX_WIDTH = 800;
    var MAX_HEIGHT = 600;
    var width = img.width;
    var height = img.height;

    if (width > height) {
    if (width > MAX_WIDTH) {
        height *= MAX_WIDTH / width;
        width = MAX_WIDTH;
    }
    } else {
    if (height > MAX_HEIGHT) {
        width *= MAX_HEIGHT / height;
        height = MAX_HEIGHT;
    }
    }
    canvas_e.width = width;
    canvas_e.height = height;
    ctx.drawImage(img, 0, 0, width, height);


    //Push Data
    var dataurl = canvas_e.toDataURL("image/png");
    console.log(dataurl);

}

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="utf-8" http-equiv="encoding">
    <!-- CSS -->
    <link href="css/main.css" rel="stylesheet" type="text/css" >
    </head>
    <body>  
      <input type="file" id="add_img" onchange="resize_img()">
      <canvas id="canvas_img"></canvas> 
      <!-- JS -->
      <script src="js/main.js" type="text/javascript"></script> 
    </body>
</html>
Was it helpful?

Solution

put the canvas code in img.onload=function () {.... }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top