简体   繁体   English

如何通过 JavaScript 截取元素?

[英]How to take a screenshot of an element via JavaScript?

I'm building a gradient picker app.我正在构建一个渐变选择器应用程序。 One of the features that I'd like to have is to save the gradient as a digital image (.jpg if possible) to the users' PC.我想要的功能之一是将渐变保存为数字图像(如果可能的话,.jpg)到用户的 PC。 On button click, it should capture a div styled with linear-gradient property and save it (classic save as popup modal).单击按钮时,它应该捕获具有线性渐变属性样式的 div 并将其保存(经典另存为弹出模式)。 I've tried many times, solutions and examples, but none of them worked.我已经尝试了很多次,解决方案和示例,但都没有奏效。 I'd like to know the easiest way of doing this with an explanation and only in plain JS if possible (no jQuery, etc).我想知道最简单的解释方法,如果可能的话,只能用普通的 JS(没有 jQuery 等)。 For some context, here are some references:对于某些情况,这里有一些参考资料:

page

HTML: HTML:

<div class="gradient-div" id="gradient-div">

CSS: CSS:

background: linear-gradient(90deg, #4CA1AF, #C4E0E5);

*the div is height: 100vh; * div 为height: 100vh; for this sole purpose (so the user can have the biggest resolution picture) and the nav, from the image, is position: fixed;仅出于此目的(因此用户可以获得最大分辨率的图片),并且图像中的导航是position: fixed;

JS tweaks the gradient orientation an color. JS 将渐变方向调整为一种颜色。

html2canvas can do that for you. html2canvas可以为您做到这一点。 It's a simple enough library that takes the contents of an element and creates a <canvas> out of it.这是一个足够简单的库,它获取元素的内容并从中创建一个<canvas> You can then export it as a PNG by calling .toDataURL('image/png') on the canvas.然后,您可以通过在 canvas 上调用.toDataURL('image/png')将其导出为 PNG。 I think it supports a few other image formats as well.我认为它也支持其他一些图像格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM