前提・実現したいこと
Canvas 上の SVG 画像を そのまま PNG画像に変化して
最初の SVG 画像のとなりに表示させようと調べていますが
うまく作動しません。
どのように直せば、SVG と PNG画像を、両方とも同時に画面上に出せるか
よろしくご指導ください。
発生している問題
作動せず
該当のソースコード
<!DOCTYPE html> <html> <head> <script> function changeColor() { document.getElementById("box01" ).style.backgroundColor = "orange" ; } </script> </head> </html> <body> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 460 380" width="460" height="380"> <style> .w00 { width: 100px; } .h00 { height: 50px; } .green0 { background-color: green ; } </style> <g> <foreignObject width='100%' height='100%' ></g> </svg> <br> <button class= " " onclick= "changeColor() " > change color </button><div xmlns="http://www.w3.org/1999/xhtml"> <div id="box01" class="w00 h00 green0 " > </div> </div> </foreignObject>
<br><br>
<button class= " " onclick= "ToPNG() " > SVG to PNG
</button>
// read SVG
const canvasEl = document.getElementById('canvas');
const context = canvasEl.getContext('2d');
const imageEl = new Image();
// SVG to Blob to URL
const staticSvgBlob
= new Blob(['<svg xmlns...'], { type: 'image/svg+xml' });
const url = URL.createObjectURL(staticSvgBlob);
// SVG to canvas
imageEl.onload = () =>
{
context.clearRect(0, 0, canvasEl.width, canvasEl.height);
context.drawImage(imageEl, 0, 0);
URL.revokeObjectURL(url); // URL to release
};
</script> <script> // js-2: SVG to PNG function ToPNG() { var svgString = new XMLSerializer().serializeToString( document.querySelector('svg')); var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var DOMURL = self.URL || self.webkitURL || self; var img = new Image(); var svg = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"}); var url = DOMURL.createObjectURL(svg); img.onload = function() { ctx.drawImage(img, 0, 0); var png = canvas.toDataURL("image/png"); document.querySelector('#png-container').innerHTML = '<img src="' + png + '"/>' ; DOMURL.revokeObjectURL( png ); }; img.src = url; } </script> </footer> </html>imageEl.crossOrigin = 'Anonymous'; imageEl.src = url;
あなたの回答
tips
プレビュー