How To Convert Html Code Or Data Containing (image Tag And Some Text) Into Image For Download
I want to render some Html code as an image to download for my website. I am using html2canvas that is working fine to create image for text but I want to create image from html di
Solution 1:
Use rasterizeHTML.js:
From the example:
<canvasid="canvas"width="400"height="200"></canvas><scripttype="text/javascript">
var canvas = document.getElementById("canvas");
rasterizeHTML.drawHTML(
'<div><h1>HTML content to render:</h1>' +
' <divid="content">' +
' <imgsrc="./images/127597554.jpg"height="200"width="200">' +
' Hello <strong>visiting</strong> guest' +
' </div>' +
'</div>',
canvas);
</script>
Or just:
rasterizeHTML.drawURL("http://example.net", canvas);
To download the image use canvas2image (with a hidden canvas):
Canvas2Image.saveAsPNG(canvas, width, height);
The major advantages of doing the rendering on the client are that the html can be user specific and the server does not have to render the image.
Solution 2:
You can embed the html in a svg to render it at the canvas, e.g.
html:
<canvas id="canvas" style="border:2px solid black;" width="160" height="43"></canvas>
js:
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;">' +
'SO</span>' +
'</div>' +
'</foreignObject>' +
'</svg>';
varDOMURL = window.URL || window.webkitURL || window;
var img = newImage();
var svg = newBlob([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;
fiddle: https://jsfiddle.net/qkvu7fmL/
I couldn't find a reference to the original source of this example- if somebody knows- please add credits as comments.
Post a Comment for "How To Convert Html Code Or Data Containing (image Tag And Some Text) Into Image For Download"