IT박스

JavaScript로 div의 스크린 샷을 만드는 방법은 무엇입니까?

itboxs 2020. 6. 8. 21:11
반응형

JavaScript로 div의 스크린 샷을 만드는 방법은 무엇입니까?


"HTML 퀴즈"라는 것을 만들고 있습니다. JavaScript에서 완전히 실행되었으며 꽤 멋집니다.

마지막에 "Your Results :"라는 결과 상자가 나타나고 소요 시간, 소요 비율 및 10 개 중 몇 가지 질문이 표시되는지 나타냅니다. 버튼이 있습니다. "결과 캡처"를하여 어떻게 든 스크린 샷이나 div를 캡처 한 다음 페이지에서 캡처 한 이미지를 마우스 오른쪽 단추로 클릭하고 "다른 이름으로 이미지 저장"을 표시하십시오.

나는 그들이 다른 사람들과 결과를 공유 할 수 있도록 정말로 이것을하고 싶습니다. 나는 그들이 쉽게 변경할 수 있기 때문에 결과를 "복사"하기를 원하지 않습니다. 그들이 이미지에서 말하는 것을 바꾸면, 오 잘.

누구든지 이것을하거나 비슷한 것을하는 방법을 알고 있습니까?


아니요, 요소를 '스크린 샷'하는 방법을 모르지만 퀴즈 결과를 캔버스 요소에 그린 다음 HTMLCanvasElement객체의 toDataURL함수를 data:사용하여 이미지 내용 이 포함 된 URI 를 얻는 것이 좋습니다.

퀴즈가 끝나면 다음과 같이하십시오.

var c = document.getElementById('the_canvas_element_id');
var t = c.getContext('2d');
/* then use the canvas 2D drawing functions to add text, etc. for the result */

사용자가 "캡처"를 클릭하면 다음과 같이하십시오.

window.open('', document.getElementById('the_canvas_element_id').toDataURL());

그러면 '스크린 샷'이 포함 된 새 탭 또는 창이 열리고 사용자가 저장할 수 있습니다. '다른 이름으로 저장'대화 상자를 호출 할 수있는 방법이 없으므로 이것이 내 의견으로는 할 수있는 최선의 방법입니다.


이것은 html2canvasFileSaver.js를 사용하여 @Dathan답변을 확장 한 것입니다 .

$(function() { 
    $("#btnSave").click(function() { 
        html2canvas($("#widget"), {
            onrendered: function(canvas) {
                theCanvas = canvas;


                canvas.toBlob(function(blob) {
                    saveAs(blob, "Dashboard.png"); 
                });
            }
        });
    });
});

이 코드 블록은 ID btnSave가있는 버튼이 클릭 될 때까지 기다립니다 . 이 경우 widgetdiv를 캔버스 요소 로 변환 한 다음 saveAs () FileSaver 인터페이스 (기본적으로 지원하지 않는 브라우저의 FileSaver.js를 통해)를 사용하여 "Dashboard.png"라는 이미지로 div를 저장합니다.

이 작업의 예는이 바이올린 에서 사용할 수 있습니다 .


몇 시간의 연구 끝에 마침내 origin-cleanFLAG가 설정되어 있어도 (XSS를 방지하기 위해) 요소의 스크린 샷을 찍을 수있는 솔루션을 찾았 으므로 Google지도 (내 경우)를 캡처 할 수도 있습니다. 스크린 샷을 얻는 범용 함수를 작성했습니다. 또한 필요한 것은 html2canvas 라이브러리 ( https://html2canvas.hertzen.com/ ) 뿐입니다 .

예:

getScreenshotOfElement($("div#toBeCaptured").get(0), 0, 0, 100, 100, function(data) {
    // in the data variable there is the base64 image
    // exmaple for displaying the image in an <img>
    $("img#captured").attr("src", "data:image/png;base64,"+data);
}

명심 console.log()하고 alert()이미지의 크기가 큰 경우 출력을 생성 이뤄져.

함수:

function getScreenshotOfElement(element, posX, posY, width, height, callback) {
    html2canvas(element, {
        onrendered: function (canvas) {
            var context = canvas.getContext('2d');
            var imageData = context.getImageData(posX, posY, width, height).data;
            var outputCanvas = document.createElement('canvas');
            var outputContext = outputCanvas.getContext('2d');
            outputCanvas.width = width;
            outputCanvas.height = height;

            var idata = outputContext.createImageData(width, height);
            idata.data.set(imageData);
            outputContext.putImageData(idata, 0, 0);
            callback(outputCanvas.toDataURL().replace("data:image/png;base64,", ""));
        },
        width: width,
        height: height,
        useCORS: true,
        taintTest: false,
        allowTaint: false
    });
}

"다른 이름으로 저장"대화 상자를 원한다면 PHP 헤더로 이미지를 전달하면 적절한 헤더가 추가됩니다.

"올인원"스크립트 예 script.php

<?php if(isset($_GET['image'])):
    $image = $_GET['image'];

    if(preg_match('#^data:image/(.*);base64,(.*)$#s', $image, $match)){
        $base64 = $match[2];
        $imageBody = base64_decode($base64);
        $imageFormat = $match[1];

        header('Content-type: application/octet-stream');
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false); // required for certain browsers
        header("Content-Disposition: attachment; filename=\"file.".$imageFormat."\";" ); //png is default for toDataURL
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".strlen($imageBody));
        echo $imageBody;
    }
    exit();
endif;?>

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js?ver=1.7.2'></script>
<canvas id="canvas" width="300" height="150"></canvas>
<button id="btn">Save</button>
<script>
    $(document).ready(function(){
        var canvas = document.getElementById('canvas');
        var oCtx = canvas.getContext("2d");
        oCtx.beginPath();
        oCtx.moveTo(0,0);
        oCtx.lineTo(300,150);
        oCtx.stroke();

        $('#btn').on('click', function(){
            // opens dialog but location doesnt change due to SaveAs Dialog
            document.location.href = '/script.php?image=' + canvas.toDataURL();
        });
    });
</script>

var shot1=imagify($('#widget')[0], (base64) => {
  $('img.screenshot').attr('src', base64);
});

htmlshot package 살펴본 다음 클라이언트 측 섹션 자세히 확인 하십시오.

npm install htmlshot

스크린 샷을 찍을 수는 없습니다. 그렇게하는 것은 무책임한 보안 위험입니다. 그러나 다음을 수행 할 수 있습니다.

  • 서버 측에서 작업하고 이미지 생성
  • Canvas와 비슷한 것을 그리고 그것을 지원하는 브라우저에서 이미지로 렌더링
  • 다른 그림 라이브러리를 사용하여 이미지에 직접 그리십시오 (느리지 만 모든 브라우저에서 작동합니다)

Another alternative is to use GrabzIt's JavaScript API all you need to do is pass the CSS selector of the div you want to capture. It will then create a screenshot of just that div.

<script type="text/javascript" src="grabzit.min.js"></script>
<script type="text/javascript">
GrabzIt("YOUR APPLICATION KEY").ConvertURL("http://www.example.com/quiz.html",
{"target": "#results", "bheight": -1, "height": -1, "width": -1}).Create();
</script>

There is more examples here solving how to capture HTML elements. For full disclosure I am the API creator.


<script src="/assets/backend/js/html2canvas.min.js"></script>


<script>
    $("#download").on('click', function(){
        html2canvas($("#printform"), {
            onrendered: function (canvas) {
                var url = canvas.toDataURL();

                var triggerDownload = $("<a>").attr("href", url).attr("download", getNowFormatDate()+"电子签名详细信息.jpeg").appendTo("body");
                triggerDownload[0].click();
                triggerDownload.remove();
            }
        });
    })
</script>

quotation


As far as I know you can't do that, I may be wrong. However I'd do this with php, generate a JPEG using php standard functions and then display the image, should not be a very hard job, however depends on how flashy the contents of the DIV are


It's to simple you can use this code for capture the screenshot of particular area you have to define the div id in html2canvas. I'm using here 2 div-:

div id="car"
div id ="chartContainer"
if you want to capture only cars then use car i'm capture here car only you can change chartContainer for capture the graph html2canvas($('#car') copy and paste this code

<html>
    <head>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
<script>
    window.onload = function () {
    
    var chart = new CanvasJS.Chart("chartContainer", {
        animationEnabled: true,
        theme: "light2",
        title:{
            text: "Simple Line Chart"
        },
        axisY:{
            includeZero: false
        },
        data: [{        
            type: "line",       
            dataPoints: [
                { y: 450 },
                { y: 414},
                { y: 520, indexLabel: "highest",markerColor: "red", markerType: "triangle" },
                { y: 460 },
                { y: 450 },
                { y: 500 },
                { y: 480 },
                { y: 480 },
                { y: 410 , indexLabel: "lowest",markerColor: "DarkSlateGrey", markerType: "cross" },
                { y: 500 },
                { y: 480 },
                { y: 510 }

            ]
        }]
    });
    chart.render();
    
    }
</script>
</head>

<body bgcolor="black">
<div id="wholebody">  
<a href="javascript:genScreenshotgraph()"><button style="background:aqua; cursor:pointer">Get Screenshot of Cars onl </button> </a>

<div id="car" align="center">
    <i class="fa fa-car" style="font-size:70px;color:red;"></i>
    <i class="fa fa-car" style="font-size:60px;color:red;"></i>
    <i class="fa fa-car" style="font-size:50px;color:red;"></i>
    <i class="fa fa-car" style="font-size:20px;color:red;"></i>
    <i class="fa fa-car" style="font-size:50px;color:red;"></i>
    <i class="fa fa-car" style="font-size:60px;color:red;"></i>
    <i class="fa fa-car" style="font-size:70px;color:red;"></i>
</div>
<br>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

<div id="box1">
</div>
</div>>
</body>

<script>

function genScreenshotgraph() 
{
    html2canvas($('#car'), {
        
      onrendered: function(canvas) {

        var imgData = canvas.toDataURL("image/jpeg");
        var pdf = new jsPDF();
        pdf.addImage(imgData, 'JPEG', 0, 0, -180, -180);
        pdf.save("download.pdf");
        
      
      
      }
     });

}

</script>

</html>


As far as I know its not possible with javascript.

What you can do for every result create a screenshot, save it somewhere and point the user when clicked on save result. (I guess no of result is only 10 so not a big deal to create 10 jpeg image of results)

참고URL : https://stackoverflow.com/questions/6887183/how-to-take-screenshot-of-a-div-with-javascript

반응형