How to take screenshot of a div with JavaScript?

前端 未结 10 1500
误落风尘
误落风尘 2020-11-22 08:03

I am building something called the \"HTML Quiz\". It\'s completely ran on JavaScript and it\'s pretty cool.

At the end, a results box pops up that says \"Your Result

10条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 08:30

    No, I don't know of a way to 'screenshot' an element, but what you could do, is draw the quiz results into a canvas element, then use the HTMLCanvasElement object's toDataURL function to get a data: URI with the image's contents.

    When the quiz is finished, do this:

    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 */
    

    When the user clicks "Capture", do this:

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

    This will open a new tab or window with the 'screenshot', allowing the user to save it. There is no way to invoke a 'save as' dialog of sorts, so this is the best you can do in my opinion.

提交回复
热议问题