简体   繁体   中英

Is there in Jquery or Dojo or plain JavaScript way to convert div to image?

Is there in Jquery or Dojo or pure JavaScript way to convert div to image? Extension of image is arbitrary.

You could create an empty div and create a class with the background-image property set to your image. Then, using jQuery or Dojo, add the class to your div.

.myImage {
  background-image: url(image.png);
  background-repeat: no-repeat;
}

<div id="myDiv"></div>

$('#myDiv').addClass('myImage');

Yes, there is, but it's tricky and maybe impossible to get it to render exactly as it appears on the page unless the div element and its appearance as possibly defined in CSS are defined in a manner than can fully stand-alone from the page.

  1. Embed the desired HTML into SVG as a foreign object.
  2. Draw the image. (These two steps are summarized here https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas?redirectlocale=en-US&redirectslug=Web%2FHTML%2FCanvas%2FDrawing_DOM_objects_into_a_canvas )
  3. Obtain the canvas data using getImageData()
  4. Encode the data into the desired image format (or send the stream of data to the server encoded as base64 (step 3 and 4 can be done as one step by using toDataURL )

An example image format easy to work with on one's own is the Unix PNM (PBM, PGM, and PPM) formats which can be sent as ASCII data.

P2
# foo.pgm
18 7
9
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 3 3 3 3 0 0 6 6 6 6 0 0 9 9 9 9 0
0 3 0 0 0 0 0 6 0 0 6 0 0 9 0 0 9 0
0 3 3 3 0 0 0 6 0 0 6 0 0 9 0 0 9 0
0 3 0 0 0 0 0 6 0 0 6 0 0 9 0 0 9 0
0 3 0 0 0 0 0 6 6 6 6 0 0 9 9 9 9 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

(Enlarged 20x: http://www.codelib.net/html/foo.png )

Stealing from https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement to show you an example of using toDataURL to output PNG image data:

function test() {
 var canvas = document.getElementById("canvas");
 var url = canvas.toDataURL();

 var newImg = document.createElement("img");
 newImg.src = url;
 document.body.appendChild(newImg);
}

Another way is to build upon the work done by html2canvas:

create screenshot of webpage using html2canvas (unable to initialize properly)

The accepted answer there shows how to screenshot the HTML body element, but it could easily be modified to "screenshot" the contents of a div by modifying the jQuery selector on the first line of the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM