How to get a PNG image of a CSS style element using a canvas with a transparent background?

I want to use CSS to style an element on a web page, and then use that element as a static png. Is it possible to draw an html node e.g. Canvas and save such an image with transparency to a file?

I want to find a way to take existing HTML with CSS and make it transparent to a PNG file.

+5
source share
2 answers

Saving HTML elements for images requires a tricky answer!

-, HTML-. , , script, HTML, + - !

, IE HTML- - .

Chrome Firefox (!), HTML- : 1. HTML SVG, "foreignObject". 2. SVG Canvas. 3. canvas.toDataURL('image/png), , png-.

, HTML, , "" HTML, PhantomJs.org(phantomjs.org). Phantomjs HTML-. PhantomJs , . , -, HTML, , 1 PhantomJs png :

phantomjs rasterize.js http://myHtmlOnMyPage.html myHtmlImage.png

Chrome/Firefox : https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas

:

<!DOCTYPE html>
<html>
<body>
<p><canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var data = "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
             "<foreignObject width='100%' height='100%'>" +
               "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>" +
                 "<em>I</em> like <span style='color:white; text-shadow:0 0 2px blue;'>cheese</span>" +
               "</div>" +
             "</foreignObject>" +
           "</svg>";
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);
};
img.src = url;
</script>
</body>
</html>
+7

All Articles