Home > Software engineering >  .drawimage() is only showing the bottom left corner of an image
.drawimage() is only showing the bottom left corner of an image

Time:01-07

I am tring to crop an image with the HTML canavas. The canvas only shows the bottom left corner of the image. How would I fix it so that it shows the entire image? What 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 returns X,Y,Height,Length

CodePudding user response:

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: "http://i.stack.imgur.com/UFBxY.png"})
<canvas id="canvas"></canvas>

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

  •  Tags:  
  • Related