2

I am building a web app that needs to export a div to an image. That div will contain images, other divs, text with css styling, etc. At the end, the user should have an image that would look the same as if he had taken a screenshot of that div. I 've looked into server-side php libs but I don't see anything that would handle the complexity of the rendered HTML. HTML5 canvas has that capability but I can't use a canvas for my case. Any ideas?

Thanks!

Mankoun
  • 41
  • 1
  • 4
  • you need a browser to render the image (kind of like browsershots.org). You could then use a chrome/ff extension to take an image. You could even automate this on the server side with something like Selenium. – DanJ Aug 27 '11 at 22:53
  • 1
    > *I can't use a canvas for my case* Why not? – Crescent Fresh Aug 27 '11 at 23:15
  • this: test doesn't print anything. I am not so familiar with but i am assuming its just for drawing and not wrapping html – Mankoun Aug 27 '11 at 23:22
  • you could look into a rendering engine like [phantomjs](http://code.google.com/p/phantomjs/), and there are quite a few others that do HTML-to-PDF, so those might work for images as well. – ldg Aug 27 '11 at 23:28

3 Answers3

4

Check out html2canvas. A javascript framework that renders the page content on a canvas element.

Bhavika
  • 540
  • 1
  • 7
  • 16
0

I've written a project that converts HTML with CSS styles to canvas.

It is available here: https://github.com/coolbloke1324/html-to-canvas

And an example test page is available here: http://www.isogenicengine.com/html-canvas/test/index.html

On the test page, the initial load will just show a square div with some other divs inside it with various stylings like backgrounds and borders including border radius etc. You'll see a button on the top-right of the page marked "Render". Click that and a canvas will be created and then the DOM will be parsed and rendered to the canvas. I intentionally changed the background colour of the canvas to black so you can see the difference.

Rob Evans
  • 6,750
  • 4
  • 39
  • 56
0

You could wrap the div in a canvas tag, access the pixel data directly, send that to a PHP script and use the data to construct an image.

Here's how you get the pixel data https://developer.mozilla.org/en/html/canvas/pixel_manipulation_with_canvas

And here's what you would use to create an image pixel by pixel http://php.net/manual/en/function.imagesetpixel.php

gargantuan
  • 8,888
  • 16
  • 67
  • 108
  • That won't work at all I'm afraid. If you wrap any HTML in a canvas tag it will no longer be rendered by the DOM unless your browser has no canvas support. Even if it were to be rendered, the canvas image data is not affected by elements that are child nodes of the canvas element so no image data would be retrieved by using getImageData() since it's a blank canvas! – Rob Evans Nov 13 '12 at 09:50