Question

I'm using the function below to resize and image using canvas

var img = new Image();
img.src = reader.result;
img.onload = function() {

    var max_width = 800;
    var max_height = 800;
    var tempW = img.width;
    var tempH = img.height;
     var aspect_ratio = 1;
    if (tempW > tempH) {
        if (tempH > max_height){
          var aspect_ratio = tempH / max_height
                       }
    } else {

            if (tempW > max_width){
          var aspect_ratio = tempW / max_width
                       }


    }
    tempH = tempH / aspect_ratio;
    tempW = tempW / aspect_ratio;

    var canvas = document.createElement('canvas')
     canvas.id = "uploadedcanvas";
    canvas.width = tempW;
    canvas.height = tempH;
    var ctx = canvas.getContext("2d");
ctx.fillStyle="#FFFFFF";
    ctx.fillRect(0,0,tempW,tempH); 
    ctx.drawImage(this, 0, 0, tempW, tempH);
    var dataURL = canvas.toDataURL("image/jpeg");

   createsecondimage(dataURL,tempW,tempH,max_width,max_height,canvas)


   }

This is able to resize an image from taken from file reader. I would like to create a second image in the same canvas using the dataURL as the image source but this it does not seem to work this is what I'm doing

    function createsecondimage(dataURL,tempW,tempH,max_width,max_height,canvas){
var copy = document.createElement('canvas');
    copy.width = max_width;
    copy.height = max_height;
    var copyctx = copy.getContext("2d");
var sx = (tempW - max_width) / 2
    var sy = (tempH - max_height) /2
   copyctx.fillStyle="#FFFFFF";
    copyctx.fillRect(0,0,max_width,max_height); 
   var imgcopy = new Image();
        imgcopy.src = dataURL;
        imgcopy.onload = function() {
      copyctx.drawImage(imgcopy, sx, sy, 800, 800,0, 0, 800, 800);
var dataURL_ = copy.toDataURL("image/jpeg");

        }

However datURL_ appears to be empty. I'm not sure why this is the case. Ideally I would want to create a new image using the image that was just resized.

Was it helpful?

Solution

You can do the following two changes and it should work:

  • set imgcpy.src after onload.
  • Use copyctx.drawImage(this, ...) instead of imgcopy.

This way you are making sure decoding and setting of image is not completed before onload is called, and this will have a valid reference to the image being decoded.

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