Rendering HTML elements to

前端 未结 6 2137
天命终不由人
天命终不由人 2020-11-28 03:53

Is there a way to have an arbitrary HTML element rendered in a canvas (and then access its buffer...).

6条回答
  •  广开言路
    2020-11-28 04:21

    Here is code to render arbitrary HTML into a canvas:

    function render_html_to_canvas(html, ctx, x, y, width, height) {
        var xml = html_to_xml(txt);
        xml = xml.replace(/\#/g, '%23');
        var data = "data:image/svg+xml;charset=utf-8,"+'' +
                            '' +
                            xml+
                            '' +
                            '';
    
        var img = new Image();
        img.onload = function () {
            ctx.drawImage(img, x, y);
        }
        img.src = data;
    }
    
    function html_to_xml(html) {
        var doc = document.implementation.createHTMLDocument('');
        doc.write(html);
    
        // You must manually set the xmlns if you intend to immediately serialize     
        // the HTML document to a string as opposed to appending it to a
        //  in the DOM
        doc.documentElement.setAttribute('xmlns', doc.documentElement.namespaceURI);
    
        // Get well-formed markup
        html = (new XMLSerializer).serializeToString(doc.body);
        return html;
    }
    

    example:

    const ctx = document.querySelector('canvas').getContext('2d');
    const html = `
    

    this

    is not

    xml!

    `; render_html_to_canvas(html, ctx, 0, 0, 300, 150); function render_html_to_canvas(html, ctx, x, y, width, height) { var data = "data:image/svg+xml;charset=utf-8," + '' + '' + html_to_xml(html) + '' + ''; var img = new Image(); img.onload = function() { ctx.drawImage(img, x, y); } img.src = data; } function html_to_xml(html) { var doc = document.implementation.createHTMLDocument(''); doc.write(html); // You must manually set the xmlns if you intend to immediately serialize // the HTML document to a string as opposed to appending it to a // in the DOM doc.documentElement.setAttribute('xmlns', doc.documentElement.namespaceURI); // Get well-formed markup html = (new XMLSerializer).serializeToString(doc.body); return html; }

提交回复
热议问题