Convert Html to Canvas

Asked

Viewed 637 times

3

Is it possible to convert an html page to canvas? For example, I have a page built in Html5 and wanted this page to be all "minified" for just one tag ?

I don’t want the html page to become an image. Ps.: Question of level of knowledge.

2 answers

5

Canvas does not render HTML, only "images". There are some libraries that may try to convert HTML into images, such as html2canvas.

However, you can create a Web Component to have "a page in a tag".

In the example below, you can see three technologies working together:

  1. Templates: sets an HTML snippet to be reused
  2. Custom Elements: registers a new tag (element) and how it will be rendered
  3. Shadow DOM: isolates the element tree and the styles that are inside an element, in this case, our component

document.registerElement('super-componente', { 
  prototype: Object.create(HTMLElement.prototype, {
    createdCallback: {
      value: function() {
        var template = document.querySelector('#super-componente');
        console.log(template);
        var clone = document.importNode(template.content, true);
        this.createShadowRoot().appendChild(clone);
      }
    }
  })
});
<template id="super-componente">
  <style>
    * { color: red }
  </style>
  <div>
    <content></content>
  </div>
</template>

<h1>Minha página</h1>
<super-componente>
  <h2>Título 1</h2>
  <p>conteúdo 1</p>
</super-componente>
<super-componente>
  <h2>Título 2</h2>
  <p>conteúdo 2</p>
</super-componente>

You can even leave the component in another HTML file and import it into other pages like this:

<link rel="import" href="super-componente.html">

Behold another example more complex of a web component I created these days in a separate file:

<template id="mmd-preview-template">
    <style>
        @import url("<?php echo plugin_dir_url(__FILE__); ?>css/editor-preview.css");
<?php if (file_exists(wp_get_theme()->get_template_directory() . '/mmd-preview-editor.css')) { ?>
        @import url("<?php echo wp_get_theme()->get_template_directory_uri(); ?>/mmd-preview-editor.css");
<?php } ?>
    </style>
    <div class='mmd-preview-content prettyprint'></div>
</template>
<?php if (file_exists(wp_get_theme()->get_template_directory() . '/mmd-preview-editor.js')) { ?>
<script type="text/java" src=""<?php echo wp_get_theme()->get_template_directory_uri(); ?>/mmd-preview-editor.js""></script>
<?php } ?>
<script>
    var mmd_template = document.currentScript.ownerDocument.querySelector('#mmd-preview-template');
    var mmdPreview = document.registerElement('mmd-preview', {
        prototype: Object.create(HTMLElement.prototype, {
            createdCallback: {
                value: function() {
                    var root = this.createShadowRoot();
                    var clone = document.importNode(mmd_template.content, true);
                    root.appendChild(clone);
                }
            },
            content: {
                value: function() {
                    return this.shadowRoot.querySelector('.mmd-preview-content').innerHTML;
                }
            },
            update: {
                value: function(content) {
                    this.shadowRoot.querySelector('.mmd-preview-content').innerHTML = content;
                    this.dispatchEvent(new CustomEvent('previewComponentUpdated', { detail: {
                        'element': this.shadowRoot.querySelector('.mmd-preview-content'),
                        'content': content
                    }}));
                    var changedElement = this.shadowRoot.querySelector('.mmd-changed');
                    if (changedElement) {
                        this.dispatchEvent(new CustomEvent('previewComponentElementChanged', { detail: {
                            'element': changedElement
                        }}));
                    }
                }
            }
        })
    });
</script>
  • utluiz, I asked this question why Google uses this in displaying images of Google Maps locations. Access this link and Inspecione, please.https://www.google.com/maps/place/Av.+ Paulista,+S%C3%A3o+Paulo+-+SP/@-23.563023,-46.65355,3a,75y,90t/data=! 3m8! 1e2!3m6! 1s20046681! 2e1! 6s%2F%2Flh4.googleusercontent.com%2Fproxy%2FoT_qW23gpoFm03kOgUkE2Zp29dc8n54Ro0SOZhgKt2u7MxFvAQTRKNDkk8-53XySuCYPFJXcIRi4A5bI0mAw0fU4Hd8FnA%3Dw203-h152! 7i3072! 8i2304! 4m2! 3m1! 1s0x94ce59c8da0aa315:0xd59f9431f2c9776a

  • @Daviddamasceno I don’t see any element inside the <canvas>. However, nothing prevents the page from putting tags over the canvas through placement. But it’s not inside, just visually superimposing,

0

<!DOCTYPE html> 
<html> 
<head>
<meta charset="utf-8">
<title> </title>
</head> 
<body>
<canvas id="canvas" title="canvas" style="outline: 1px solid red;"></canvas>
<div style="background-color: red">teste</div>
<div style="background-color: green">teste</div>
<div style="background-color: blue">teste</div>
</body>
</html>

<script>
document.body.onload = function(){ htmL() }

function htmL(){
html = document.documentElement

height = Math.max( document.body.scrollHeight, document.body.offsetHeight, 
                       html.clientHeight, html.scrollHeight, html.offsetHeight )
width  = Math.max( document.body.scrollWidth, document.body.offsetWidth, 
                       html.clientWidth, html.scrollWidth, html.offsetWidth )

html.setAttribute( 'xmlns', html.namespaceURI )
xhtml = new XMLSerializer().serializeToString( html )
concatnameSspace( xhtml, width, height )
}

function concatnameSspace( xhtml, width, height ){
svg = ''.concat( '<svg xmlns="http://www.w3.org/2000/svg" width="', width, '" height="', height, '">', 
'<foreignObject width="100%" height="100%">', xhtml, '</foreignObject></svg>' )
svgToimg( svg )
}

function svgToimg( svg ){
img = new Image()
img.onload = function(event){ imgTocanvas(event.target, event.target.naturalWidth, event.target.naturalHeight) }
img.src = 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent( svg )
}

function imgTocanvas( img, width, height ) {
canvas = document.getElementById('canvas')
canvas.width  = 147 // width
canvas.height = 210 // height
context = canvas.getContext('2d')
context.drawImage( img, 0, 0, canvas.width, canvas.height )
}
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.