如何截取网页的特定部分就像Firefox截图不使用HTML画布一样?

时间:2017-12-07 06:00:05

标签: javascript html

我需要有一个光标来拖动并在HTML网页上截取拖动区域的屏幕截图。我尝试使用HTML画布,但它截取的是特定div的屏幕截图,而不是HTML网页上的选定区域。

1 个答案:

答案 0 :(得分:3)

新的http://www.tornadoweb.org/en/stable/guide/templates.html包含widthheightxy个选项。

您可以利用这些选项来实现Firefox屏幕截图的裁剪功能。

document.onmousedown = startDrag;
document.onmouseup = endDrag;
document.onmousemove = expandDrag;

var dragging = false,
  dragStart = {
    x: 0,
    y: 0
  },
  dragEnd = {
    x: 0,
    y: 0
  };

function updateDragger() {
  dragger.classList.add('visible');
  var s = dragger.style;
  s.top = Math.min(dragStart.y, dragEnd.y) + 'px';
  s.left = Math.min(dragStart.x, dragEnd.x) + 'px';
  s.height = Math.abs(dragStart.y - dragEnd.y) + 'px';
  s.width = Math.abs(dragStart.x - dragEnd.x) + 'px';
}

function startDrag(evt) {
  evt.preventDefault();
  dragging = true;
  dragStart.x = dragEnd.x = evt.clientX;
  dragStart.y = dragEnd.y = evt.clientY;
  updateDragger();
}

function expandDrag(evt) {
  if (!dragging) return;
  dragEnd.x = evt.clientX;
  dragEnd.y = evt.clientY;
  updateDragger();
}

function endDrag(evt) {
  dragging = false;
  dragger.classList.remove('visible');
  // here is the important part
  html2canvas(document.body, {
      width: Math.abs(dragStart.x - dragEnd.x),
      height: Math.abs(dragStart.y - dragEnd.y),
      x: Math.min(dragStart.x, dragEnd.x),
      y: Math.min(dragStart.y, dragEnd.y)
    })
    .then(function(c) {
      document.body.appendChild(c);
    });
  dragStart.x = dragStart.y = dragEnd.x = dragEnd.y = 0;
}
* {
  user-select: none;
}

#dragger {
  position: fixed;
  background: rgba(0, 0, 0, .5);
  border: 1px dashed white;
  pointer-events: none;
  display: none;
}

#dragger.visible {
  display: block;
}

canvas {
  border: 1px solid;
}
<script src="https://github.com/niklasvh/html2canvas/releases/download/v1.0.0-alpha.1/html2canvas.js"></script>
<div id="wrapper">
  <p> Drag to take a screenshot ...</p>
  <img crossOrigin src="https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png" width="120" height="120">
</div>

<div id="dragger" tabindex></div>