Search code examples
javascripthtmlcanvashtml2canvas

.drawimage() is only showing the bottom left corner of an image


I am trying to crop an image with Javascript. I have croppr.js and it is sending the data and I was trying to crop the image so I can save it to a storage server with Base 64. I have read online about .drawimage(). I have tried:

function process(data) {
    console.log("DATA:" + data)
            var canvas = document.getElementById("canvas")
      var context = canvas.getContext('2d');
      var imageObj = new Image();
            var zoom 
          imageObj.onload = function() {

                context.width = data.width
                context.height = data.height

                // draw cropped image
                var sourceX = data.x;
                var sourceY = data.y;
        var sourceWidth = data.width / 2;
        var sourceHeight = data.height / 2; 
        var destWidth = sourceWidth;
        var destHeight = sourceHeight;
        var destX =  0;
        var destY =  0;
        context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
                var dataurl = canvas.toDataURL('image/jpeg', 1.0)
                console.log(dataurl)
            };
      imageObj.src = document.getElementsByTagName("img")[0].src;
            console.log(imageObj.src)
}

data Contains X Y Height Width As an JSON array.


Solution

  • First I see is the:

    context.width = data.width
    context.height = data.height
    

    Did you meant to do canvas instead?

    Here is an example:

    function process(data) {
      var canvas = document.getElementById("canvas")
      var context = canvas.getContext('2d');
      var img = new Image();
      
      img.onload = function() {
        canvas.width = data.width
        canvas.height = data.height
    
        // draw cropped image
        var w = data.width / 2;
        var h = data.height / 2;
    
        context.drawImage(img, data.x, data.y, w, h, 0, 0, w, h);
      };
      img.src = data.src;
    }
    
    process({x:0, y:0, width:600, height: 600, src: "https://i.sstatic.net/UFBxY.png"})
    <canvas id="canvas"></canvas>

    That is the only issue I could see on your code.
    What is not clear is the data you use to call the process function