Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize the screenshot function of JavaScript

Shulou Source: shulou.com Published: 2022-05-31 13:07:40 09月24日 Update

Today, the editor will share with you the relevant knowledge about how to achieve screenshot function in JavaScript. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

The media type of 1.Blob must be "image/svg+xml"

two。 A svg element is required

3. Insert a foreignObject element into the svg element

4. Put a html that conforms to the specification in the foreignObject element

Converting dom to canvas is as simple as that, just a few steps above. Here is a simple demo given by the document:

Document var canvas = document.getElementById ('canvas'); var ctx = canvas.getContext (' 2d'); var data ='+'I like'+'+ 'cheese' +'; var DOMURL = window.URL | | window.webkitURL | | window; var img = new Image (); var svg = new Blob ([data], {type: 'image/svg+xml'}); var url = DOMURL.createObjectURL (svg) Img.onload = function () {ctx.drawImage (img, 0,0); DOMURL.revokeObjectURL (url);} img.src = url

Copy the code, run it, wow, awesome, there are two cool lines of art words on the browser!

Well, it turns out that it's so easy to convert dom to canvas? Then I take out all the dom in body through document.body [XSS _ clean] and put it in the foreignObject element, so I OK and cut down the whole page.

Demo is just a Hello World, but the Dom structure in the actual project is much more complex, such as the introduction of external stylesheets, images, and possibly some tags that do not conform to the xml specification (such as the lack of closed tags, etc.). The following is a simple example. Instead of using the inline style, .container is defined in the style tag, the font is red, and the style does not take effect when converted to an image.

Document .container {color: red;} Hello World!

Tags: Styles elements pages parts facets content knowledge articles pictures that is methods tags functions functions objects ideas structures different good complex Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS MySQL MariaDB Xiaomi Docker