Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

screenshot - Compile/Save/Export HTML as a PNG Image using Jquery

I have a set-up with multiple variables that users can alter that effect a visual representation of an element. All of this is controlled by jquery scripts. It would be cool if there was a way to save the resultant image as per what the browser renders. It'd be no different than a screencapture from a user perspective, though it would only capture the relevant area.

I have a plugin for FF called Page Saver, and it's functionality is pretty much what i am looking for, but with jquery or regular javascript if possible.

I'm more asking for tips, and a general direction that you guys would advise me to go in in order to pursue such functionality. I'd prefer not to learn another language to do this, but if i must...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit : This method only works in Firefox extensions.

You can use HTML5 canvas, Firefox' drawWindow 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...