如何使用JavaScript截取div的截图? [英] How to take screenshot of a div with JavaScript?
问题描述
我正在构建一个名为HTML测验的东西。它完全在JavaScript上运行,非常酷。
I am building something called the "HTML Quiz". It's completely ran on JavaScript and it's pretty cool.
最后,弹出一个结果框,显示Your Results:,并显示他们花了多少时间,他们得到了多少百分比以及他们从10个问题中得到了多少个问题。我想要一个名为捕获结果的按钮,并以某种方式截取某个div的某个截图,然后仅显示捕获的图像他们可以右击的页面和另存为图片。
At the end, a results box pops up that says "Your Results:" and it shows how much time they took, what percentage they got, and how many questions they got right out of 10. I would like to have a button that says "Capture results" and have it somehow take a screenshot or something of the div, and then just show the image captured on the page where they can right click and "Save image as."
我真的很喜欢这样做,所以他们可以与其他人分享他们的结果。我不希望他们复制结果,因为他们可以很容易地改变结果。如果他们改变了图片中所说的话,那么很好。
I really would love to do this so they can share their results with others. I don't want them to "copy" the results because they can easily change that. If they change what it says in the image, oh well.
有没有人知道一种做法或类似的方法?
Does anyone know a way to do this or something similar?
推荐答案
不,我不知道如何截取一个元素,但是您可以做的是绘制测验结果为一个canvas元素,然后使用 HTMLCanvasElement
对象的 toDataURL
函数来获取数据:
包含图片内容的URI。
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.
这篇关于如何使用JavaScript截取div的截图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!