简体   繁体   中英

save/export image file from html content?

我有一个场景,我正在创建动态的HTML内容,我需要导出/保存html内容到一个图像文件与PHP,jQuery和JavaScript [或任何其他如果可能]。

You can use HTML5 canvas and the toDataURL method. For example:

var capture = function() {
  var root = document.documentElement;
  var canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'html:canvas');
  var context = canvas.getContext('2d');
  var selection = {
    top: 0,
    left: 0,
    width: root.scrollWidth,
    height: root.scrollHeight,
  };

  canvas.height = selection.height;
  canvas.width = selection.width;

  context.drawWindow(
    window,
    selection.left,
    selection.top,
    selection.width,
    selection.height,
    'rgb(255, 255, 255)'
  );

  return canvas.toDataURL('image/png', '');
};

You can adjust top, left, width and height to capture only a part of the web page.

The result is a data URI string. You can send it to your server or draw it on another canvas:

  var canvas = document.getElementById('captured');
  var ctx = canvas.getContext('2d');
  var image = new Image();
  image.src = capture();

  // the image is not immediately usable
  $(image).load(function() { // jquery way
    canvas.width = image.width;
    canvas.height = image.height;
    ctx.drawImage(image, 0, 0);
  });

Your plugin probably uses this method. You can also check its source code.

Edit: To send it to your server with JQuery you can do something like that:

$("#send-capture-button").click(function() {
  $.post("/url-to-send-image-to", {image_data: capture()})
});

On the server side you'll have to decode the data URL.

Based on "Michaël Witrant" answer look at : Compile/Save/Export HTML as a PNG Image using Jquery

I put the canvas myself and did not use createElement line above You probably need to add this line before drawWindow() to get security permissions from user. See http://murfy.de/read/webgl-drawWindow

netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

If you want to save the image as PNG etc, I found a useful script at: http://www.nihilogic.dk/labs/canvas2image/

After all i have decided to use the code php

GD and Image Functions

http://php.net/manual/en/ref.image.php

with this, i have created the specific html elements at specific positions with images.

thanks all for contributing.

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