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!
Check out html2canvas. A javascript framework that renders the page content on a canvas element.
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
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.