1

How can I download my div as an image? (In JavaScript, Jquery or PHP)

I have a simple HTML code:

<div id="downloadThis">
  <div style="width: 200px; height: 100px; background: red"></div>
  <div style="width: 200px; height: 100px; background: blue"></div>
</div>
<button id="downloader" onClick="download('downloadThis')">Download</button>

And I want to download it as an image:

<script>
  function download(id){
    document.getElementById(id).downloadAsImage("jpeg");
  }
</script>
gvlasov
  • 18,638
  • 21
  • 74
  • 110
Tamás
  • 950
  • 2
  • 10
  • 29

2 Answers2

1

What you see in your web browser when you open a page is the result of rendiring a page. You don't download the result of rendering, it is already on your computer and in your memory. What you are trying to do is to take a screenshot.

In Javascript, there is no standard API for taking screenshots of rendered pages — after all, it is not a job of the web browser, but rather of your system tools. But a trick you can do is to separately render a part of your DOM (or whote DOM) into <canvas> and save contents of that canvas to an image. This answer explains the general mechanics of such process: https://stackoverflow.com/a/6678156/1542343

Now, you may say that there are online services that let you download a screenshot of a website done in different browsers, but what those services essentially do is they run a browser on a server and use the operating system tools to take a screenshot of the desired page. They could as well be taking screenshots of Microsoft Word run on their servers or anything, inherently that has nothing to do with web browsers.

Community
  • 1
  • 1
gvlasov
  • 18,638
  • 21
  • 74
  • 110
1

Browsers don't let programmers export the content of Divs for very good security reasons--your banking info is likely inside a div.

What you can do is send the html+css that created the div into a library that re-renders that html+css in a way that can be imaged.

Here are 2 libraries that re-render html+css:

html2canvas uses brute force to convert all html+css into a canvas drawing. It works fine for basic content, but fails for more complex content. It too has security restrictions and cannot re-render content which was loaded from a different domain than the webpage itself. Link: http://html2canvas.hertzen.com/

PhantomJS is a server-side library that uses webkit to re-render the html+css. It will create a more true image from the html+css that you send to it because it's using webkit's browser engine to do the rendering. Link: http://phantomjs.org/

markE
  • 102,905
  • 11
  • 164
  • 176