Nesting HTML in canvas

Time:2021-12-2
It's probably like this. Now you need to generate pictures according to the uploaded pictures and some inputs. Originally, I planned to use ImageMagick, but later I felt that two different codes should be made at the front and back ends. Then ImageMagick is far less easy to use than canvas. So, we finally decided to use canvas to handle it, and then send the base64 encoding of the picture back to the back end through todataurl and save it. Here's the code.

<!DOCTYPE html>
<html>
<body>
    <img  id="pic"  style="display:none"/>
    <canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");

        //See [drawing_dom_objects_into_a_canvas] [1]
        function drawHtmlToCanvas() {
            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);
                //Chrome version does not support, currently only Firefox is supported
                console.log(canvas.toDataURL());
            };
            img.src = url;
        }

        function drawCrossOriginImg2Canvas(callback) {
            var img = new Image();
            //There is a cross domain problem with todataurl. See [CORS enabled image] [2]. The image server here should support access control allow origin
            img.crossOrigin = "Anonymous";
            img.src = document.getElementById('pic').src;
            img.onload = function(){
                ctx.drawImage(img, 0, 0);
                callback && callback();
                //Both chrome and Firefox are OK
                console.log(canvas.toDataURL());
            }
        }

        drawCrossOriginImg2Canvas(drawHtmlToCanvas);

    </script>
</body>
</html>

The question is why chrome does not support todataurl () for blobs

[1]: https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas
[2]: https://developer.mozilla.org/zh-CN/docs/CORS_Enabled_Image