[英]How to convert all elements inside html div element into an image using javascript without any third party library
I am having a div with 3 elements. 我有3个元素的div。 I want to convert that whole div into an image without using third party tool.
我想将整个div转换为图像而不使用第三方工具。 Kindly provide me any suggestion regarding this.
请给我有关此的任何建议。
<!DOCTYPE html> <html> <body> <div id="div1">DIV 1<br> <svg width="50" height="50"> <path d="M0,0 L50,0 L50,50 Z" style="stroke: #006666; fill:none;"/> </svg> <div>DIV 2</div> <input type="button" value="Button"/> </div> </body> </html>
This is probably a good starting point. 这可能是一个很好的起点。 I have slightly modified the answer from this question https://stackoverflow.com/a/27232525/8085668 .
我对这个问题的答案做了些微修改, https://stackoverflow.com/a/27232525/8085668 。 I have just removed the callback and added a click event.
我刚刚删除了回调并添加了click事件。 Please refer to it for a detailed explanation of the code.
请参考它以获取有关代码的详细说明。
var svgText = document.getElementById("myViewer").outerHTML; var myCanvas = document.getElementById("canvas"); var ctxt = myCanvas.getContext("2d"); var btn = document.getElementsByClassName('convert2Png')[0]; function drawInlineSVG(ctx, rawSVG) { var svg = new Blob([rawSVG], {type:"image/svg+xml;charset=utf-8"}), domURL = self.URL || self.webkitURL || self, url = domURL.createObjectURL(svg), img = new Image; img.onload = function () { ctx.drawImage(this, 0, 0); domURL.revokeObjectURL(url); }; img.src = url; } // usage: btn.addEventListener('click', function() { drawInlineSVG(ctxt, svgText); });
<!DOCTYPE html> <html> <body> <div id="div1">DIV 1<br> <svg width="50" height="50" id="myViewer" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"> <path d="M0,0 L50,0 L50,50 Z" style="stroke: #006666; fill:none;"/> </svg> <div>DIV 2</div> <input class="convert2Png" type="button" value="Button"/> <canvas id="canvas" width=800 height=600 style="margin-top:10px;"></canvas> </div> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.