在Canvas中嵌套Html

大概是這樣的,如今須要根據一下上傳的圖片以及一些輸入生成圖片。原本打算用imagemagick的,可是後來以爲這樣先後端要搞兩份不一樣的代碼,而後imagemagick使用起來遠沒有canvas用起來順手啊。So,最終決定就用Canvas搞定它了,而後經過toDataURL將圖片的base64編碼傳回後端再保存。下面直接上代碼。

<!DOCTYPE html>
<html>
<body>
    <img src="http://example.com/xxx.jpg"  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");

        // 參見[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版本不支持,目前只支持firefox
                console.log(canvas.toDataURL());
            };
            img.src = url;
        }

        function drawCrossOriginImg2Canvas(callback) {
            var img = new Image();
            // toDataURL存在跨域問題,參見[CORS Enabled Image][2],此處的圖片服務器要支持Access-Control-Allow-Origin
            img.crossOrigin = "Anonymous";
            img.src = document.getElementById('pic').src;
            img.onload = function(){
                ctx.drawImage(img, 0, 0);
                callback && callback();
                // chrome&firefox 都OK
                console.log(canvas.toDataURL());
            }
        }

        drawCrossOriginImg2Canvas(drawHtmlToCanvas);

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

有疑問的是問什麼chrome爲什麼對於blob:不支持toDataURL()html

[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_Imageweb

相關文章
相關標籤/搜索