简体   繁体   中英

How to take a screenshot of specific part of webpage just like Firefox screenshot not using HTML canvas?

I need to have a cursor to drag and take screenshot of dragged area on HTML webpage. I tried using HTML canvas but it takes screenshot of specific div not the selected region on HTML webpage.

The new html2canvas version 1 has width , height , x and y options.

You can make use of these options to achieve a cropping feature the Firefox's Screenshot's way.

 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> 

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