如何使用 JavaScript 截取 div 的屏幕截图? [英] How to take screenshot of a div with JavaScript?

查看:60
本文介绍了如何使用 JavaScript 截取 div 的屏幕截图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个叫做HTML 测验"的东西.它完全在 JavaScript 上运行,非常酷.

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

最后,会弹出一个结果框,上面写着您的结果:",它显示了他们花费了多少时间、他们得到的百分比以及他们在 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?

推荐答案

不,我不知道有什么方法可以截屏"元素,但您可以做的是将测验结果绘制到画布元素中,然后使用 HTMLCanvasElement 对象的 toDataURL 函数获取带有图像内容的 data: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆