ferhado
ferhado

Reputation: 2594

Draw cropped image in canvas

How to get the right position of image and draw what I see in lens into canvas? Here is my example with a demo.

var isDown,
  lens,
  img,
  canvas,
  cx,
  cy,
  ctx,
  image;

img = document.getElementById('img');
lens = document.getElementById('lens');
canvas = document.getElementById('canvas');
cx = canvas.offsetWidth / lens.offsetWidth;
cy = canvas.offsetHeight / lens.offsetHeight;

ctx = canvas.getContext('2d');
image = new Image();
image.src = img.src;

lens.addEventListener("mousemove", (e) => {
  moveLens(e);
});

img.addEventListener("mousemove", (e) => {
  moveLens(e);
});


function moveLens(e) {
  var pos, x, y;
  e.preventDefault();
  pos = getCursorPos(e);
  x = pos.x - (lens.offsetWidth / 2);
  y = pos.y - (lens.offsetHeight / 2);
  if (x > img.width - lens.offsetWidth) {
    x = img.width - lens.offsetWidth;
  }
  if (x < 0) {
    x = 0;
  }
  if (y > img.height - lens.offsetHeight) {
    y = img.height - lens.offsetHeight;
  }
  if (y < 0) {
    y = 0;
  }
  lens.style.left = x + "px";
  lens.style.top = y + "px";
  draw(x, y);
}

function getCursorPos(e) {
  var a, x = 0,
    y = 0;
  e = e || window.event;
  a = img.getBoundingClientRect();
  x = e.pageX - a.left;
  y = e.pageY - a.top;
  x = x - window.pageXOffset;
  y = y - window.pageYOffset;
  return {
    x: x,
    y: y
  };
}

function draw(x, y) {
  ctx.drawImage(image, x, y, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
}
#container {
  position: relative;
  width: 300px;
  display:inline-block;
}

#container>img {
  max-width: 100%;
}

#lens {
  position: absolute;
  border: 1px solid #d4d4d4;
  width: 80px;
  height: 80px;
}
<div id="container">
  <div id="lens"></div>
  <img src="https://cdn.pixabay.com/photo/2016/06/18/17/42/image-1465348_960_720.jpg" id="img">
</div>
<canvas width="200" height="200" id="canvas"></canvas>

Upvotes: 0

Views: 91

Answers (1)

haopeng
haopeng

Reputation: 243

ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

The sx,sy,sWidth,sHeight are measured according to the source image. Say we have an image in way HIGH resolution, for instance, 2000 * 1000, then the sWidth and sHeight should be scaled up to that resolution. In your case, it should be 80 / 300 * 2000 for sWidth.

I've made those adjustments to your code.

function draw(x, y) {
  ctx.clearRect(0, 0, canvas.width, canvas.height); // you might want to draw on a clean canvas each time
  let scaleX = x / img.offsetWidth * image.width;
  let scaleY = y / img.offsetHeight * image.height;
  let scaleWidth = lens.offsetWidth / img.width * image.width;
  let scaleHeight = lens.offsetHeight / img.height * image.height;
  ctx.drawImage(image, scaleX, scaleY, scaleWidth, scaleHeight, 0, 0, canvas.width, canvas.height);
}

Upvotes: 3

Related Questions