0

Here is the fiddle: http://jsfiddle.net/awguo/0fep62wr/4/

In this case, I will upload an image and then draw a canvas exactly above it.

Then, I will drag an 'area' (recording the mouse positions) and then draw a rectangle in the canvas to represent the mouse area that I draw.

Everything works ok except the rectangle is always not exactly fit to the area that I draw.

Is there anything I did wrong in the code?

Thanks!

Code below:

// get position
function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: (evt.clientX - rect.left),
    y: (evt.clientY - rect.top)
  };
}

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      $('#blah').attr('src', e.target.result);
      $('#base64_output').val(e.target.result);
            var $cc = $('<canvas style="cursor:crosshair;width:100%;height:100%;position:absolute;top:0;left:0">');
      var cc = $cc[0];
      cc.addEventListener('mousedown', function(e) {
        window.mousePos1 = getMousePos(cc, e);

      }, false);
      cc.addEventListener('mouseup', function(e){
        window.mousePos2 = getMousePos(cc, e);
        var p1x = window.mousePos1.x;
        var p1y = window.mousePos1.y;
        var p2x = window.mousePos2.x;
        var p2y = window.mousePos2.y;
        if (p1x > p2x) {
          var tempx = p2x;
          p2x = p1x;
          p1x = tempx;
        }
        if (p1y > p2y) {
          var tempy = p2y;
          p2y = p1y;
          p1y = tempy;
        }
        var message = "area:" + p1x +',' + p1y + ',' + p2x + ',' + p2y;
        $('#data_output').val(message);

        // draw a preview rectangle:
        var w = p2x-p1x;var h = p2y-p1y;
        var ctx=cc.getContext("2d");
        ctx.rect(p1x,p1y,w,h);
        ctx.stroke();

      }, false);
      $('#wrapper').append($cc);
    }

    reader.readAsDataURL(input.files[0]);
  }
}

$("#imgInp").change(function(){
  readURL(this);
});
AGamePlayer
  • 5,691
  • 14
  • 46
  • 84

1 Answers1

0

The problem has to do with using percentage scaling of the canvas. I'm not saying that you can't do it, but you need to realize that it causes complications, such as needing to match the image size manually, or keep track of width and height ratios, or some other strategy. This SO Q & A discusses the problem, and there are many others, on and off Stack Overflow.

If I remember right, I think that I needed to make sure that the canvas scale factor didn't get automatically set in some cases, too.

Community
  • 1
  • 1
Kent Weigel
  • 1,018
  • 1
  • 8
  • 16