Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

javascript - 如何使用JavaScript拍摄div的屏幕截图?(How to take screenshot of a div with JavaScript?)

I am building something called the "HTML Quiz".(我正在构建一个称为“ HTML测验”的东西。)

It's completely ran on JavaScript and it's pretty cool.(它完全在JavaScript上运行,非常酷。)

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."(最后,弹出一个结果框,显示“您的结果:”,它显示了他们花费了多少时间,他们得到了多少百分比以及他们从10个问题中得出了多少个问题。我想有一个按钮,上面写着“捕获结果”,并使其以某种方式截取屏幕截图或div,然后仅显示页面上捕获的图像,他们可以右键单击并“将图像另存为”。)

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?(有谁知道做到这一点的方法或类似的方法?)

  ask by Nathan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.(不,我不知道“截屏”元素的方法,但是您可以做的是将测验结果绘制到canvas元素中,然后使用HTMLCanvasElement对象的toDataURL函数获取data:带有图像内容的URI 。)

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.(无法调用各种“另存为”对话框,因此我认为这是您可以做的最好的事情。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...