简体   繁体   中英

How can I capture multiple images out of one in the <canvas>?

I wrote some code that draws a semi-transparent rectangle over an image that you can draw with touch:

function drawRect() {
  var canvas = document.getElementById('receipt');
  var ctx = canvas.getContext('2d');
  var drag = false;
  var imageObj;
  var rect = { };
  var touch;

  canvas.width = WIDTH;
  canvas.height = HEIGHT;

  function init() {
    imageObj = new Image();

    imageObj.src = 'img.jpg';
    imageObj.onload = function() {
      ctx.drawImage(imageObj, 0, 0);
    };

    canvas.addEventListener('touchstart', handleTouch, false);
    canvas.addEventListener('touchmove', handleTouch, false);
    canvas.addEventListener('touchleave', handleEnd, false);
    canvas.addEventListener('touchend', handleEnd, false);
  }

  function handleTouch(event) {
     if (event.targetTouches.length === 1) {
       touch = event.targetTouches[0];

     if (event.type == 'touchmove') {
        if (drag) {
          rect.w = touch.pageX - rect.startX;
          rect.h = touch.pageY - rect.startY ;
          draw();
        }
      } else {
        rect.startX = touch.pageX;
        rect.startY = touch.pageY;
        drag = true;
      }
    }
  }

  function handleEnd(event) {
    drag = false;
  }

  function draw() {
    drawImageOnCanvas();
    ctx.fillStyle = 'rgba(0, 100, 255, 0.2)';
    ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
  } 

  function drawImageOnCanvas() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(imageObj, 0, 0);
  }

  init();
}

This works. But, now I'd like to have it so that I can capture each of the parts of the image that are in rectangles as separate images.

How can I pull this off? Because I have that redraw stuff, it deletes the previous rectangle, which makes this difficult.

A canvas can only save out the whole canvas as an image, so the trick is to create a temporary canvas the size of the region you want to save out.

One way could be to create a function which takes the image and a rectangle object as argument and returns a data-uri (or Blob) of the region:

function saveRegion(img, rect) {

   var canvas = document.createElement("canvas"),
       ctx = canvas.getContext("2d");

   canvas.width = rect.w;
   canvas.height = rect.h;
   ctx.drawImage(img, rect.startX, rect.startY, rect.w, rect.h, 0, 0, rect.w, rect.h);

   return canvas.toDataURL():
}

You can pass in the original image if don't want any graphics on top, or if you draw elements on top of it just pass in the original canvas element as image source. And of course, CORS-restrictions apply.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM