简体   繁体   中英

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. On button click, it should capture a div styled with linear-gradient property and save it (classic save as popup modal). 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). For some context, here are some references:

page

HTML:

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

CSS:

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

*the div is height: 100vh; for this sole purpose (so the user can have the biggest resolution picture) and the nav, from the image, is position: fixed;

JS tweaks the gradient orientation an color.

html2canvas can do that for you. It's a simple enough library that takes the contents of an element and creates a <canvas> out of it. You can then export it as a PNG by calling .toDataURL('image/png') on the canvas. I think it supports a few other image formats as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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