EzDevInfo.com

html2canvas

Screenshots with JavaScript

How to make transparent color white instead of black in canvas?

I'm trying to take a screenshot using html2canvas:

var body = document.getElementById("body")
$(body).html2canvas({onrendered: function( canvas ) {  
     var urlData = canvas.toDataURL("image/jpeg");  
}});

My body's background is transparent, and therefore urlData because of jpeg has black background (not white like in browser).
How can I fix this behavior and make background color white in this case?


Source: (StackOverflow)

Using html2Canvas with HighCharts

I want to use html2canvas discussed at http://html2canvas.hertzen.com/documentation.html to convert the html content to image. However I am not getting image of HighCharts properly. On IE10 It renders blank image and on Chrome it renders a part of it. Is it possible to use html2canvas for this purpose.


Source: (StackOverflow)

Advertisements

SVG Text attribute is doubling - HTML2CANVAS

Here is mycode and link to JSFiddle.

HTML

<input type="button" id="export" value="Export"/>
    <svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink">

<text x="162" text-anchor="middle" class="highcharts-title" zindex="4" style="color:#333333;font-size:18px;font-weight:normal;text-decoration:normal;font-family:Lucida Grande,Lucida Sans Unicode, Arial, Helvetica, sans-serif;visibility:visible;fill:#333333;width:260px;" y="25">Inventory</text>
</svg>

JS

$(document).ready(function(){
        $('#export').on('click', function() {       
            html2canvas(document.body, {
                onrendered: function(canvas) {
                    document.body.appendChild(canvas);
                },
            });
        });
});

I'm trying to convert an svg to canvas image using html2canvas library. In the example I'm just appending the canvas image to the output. You can clearly see that the text is multiplied. Could anyone advice me to solve this issue.

Hope my question is clear. Thanks in advance.


Source: (StackOverflow)

html2canvas offscreen

In using html2canvas, I have a stack of DOM objects (relative positioned div's that contain various things), that I wish to create individual thumbnails for. So if there are ten divs, I will create ten thumbnails.

Some of these objects will be offscreen --each of these divs are in a single, encompassing div called "mainDiv". I iterate through the divs within mainDiv and execute the html2canvas on each of them individually.

For those that are onscreen, this works fine. Those that are offscreen do not -- they come back blank. I created a workaround that scrolls the objects to the top of the mainDiv, however this is a kludge and visually unappealing.

Is it possible to specify a DOM object that is not visible? Ideally, I'd like to be able to specify a containing div and have html2canvas ignore the parent visibility, so I can screen capture hidden objects, but barring that, I'd like to be able to screen capture objects that are simply scrolled off screen.

Any thoughts, ideas? Thanks!

---- Here is some example code. Basically, if you had a bunch of divs within a div, iterate through them. I actually do this recursively so that only one gets processed at a time, with the callback calling the recursive function, so it looks something like this:

  function recurser(anIndex, callback) {
    if (anIndex == -1) {
        callback();
        return;
    }
    $(myDivs[anIndex]).html2canvas({
        onrendered : function(canvas) {
            var img = canvas.toDataURL();
            // store the image in an array, do stuff with it, etc.
            recurser(--anIndex, callback);

        }
    })

}

Once the recursive calls are complete, it executes the callback function, which is a function that will do stuff with the images.

Again, all this works fine as long as the objects are visible within the scrolling div that contains all of the divs in #mainDiv. Once any part of the divs are scrolled off, however, they render black. In fact, if half of two divs are scrolled off (the top half of one, the bottom half of the next), they both render completely black.


Source: (StackOverflow)

ajax InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

Very strange issue...I am trying to pass multiple values to a method in post. It works fine as long as I dont post as an object. But when I try to post as an object I get the error

Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.

here is the code

This works

var x = $('#myDiv').val(canvas.toDataURL("image/png", 1.0);    
                $.ajax({
                    type:'POST',
                    url:"/myMethod/test",
                    data: x,
                    success:function (response) {
                }
            });

But this would NOT work

var x = $('#myDiv').val(canvas.toDataURL("image/png", 1.0);    
                    $.ajax({
                        type:'POST',
                        url:"/myMethod/test",
                        data: {x:x}, 
                        success:function (response) {
                        }
                    });

I am not sure why it is complaining when I try to send it as an object


Source: (StackOverflow)

html2canvas does not work with Google Maps Pan

I'm using html2canvas to save my online map as an image (See the Save as Image link). I've tried it in Firefox, Chrome and Opera.

It tends to work more often if you do not alter the default map. If you zoom and then pan the map, it is less likely to work. The map will pan, but html2canvas will use the old center point and map bounds. And html2canvas will fail to load map tiles for the new map bounds.

The map pans correctly, but html2canvas uses the old center point and map bounds. Why is this?

To support getting images from different domains I have the setting:

useCors: true;

I have tried the following solutions

-Manually changing the map type. Sometimes this fixes it.

-Triggering the browser resize event - not useful.

-Using setTimeout() to wait 2000 ms to ensure the tiles are loaded - not useful

-Using a proxy (html2canvas_proxy_php.php) - not useful

-Using the google maps idle event to wait for the map to be idle before saving - not useful


Source: (StackOverflow)

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

I am attempting to use http://html2canvas.hertzen.com/ to take screenshots of my webpage. I am unable to initialize a canvas element using...

var canvas = $('body').html2canvas();

If I were able to get a proper canvas I would follow with something like

var dataUrl = canvas.toDataURL(); //get's image string
window.open(dataUrl);             // display image

Unfortunately, the documentations is very limited IMO. http://html2canvas.hertzen.com/documentation.html . I do not believe I need to preload as I am not using any dynamic graphics(but am not even getting that far anyways)

I am simply too noob to understand if this guy is having success with screen capturing using html2canvas

I don't seem to be getting any farther than this fellow.. How to upload a screenshot using html2canvas?

My ideal solution would demonstrate how to create screenshot with minimal code. (Copy html to canvas. get toDataURL string. output string)

ANY insight is GREATLY appreciated =)


Source: (StackOverflow)

html2canvas not capturing image

html2canvas.js not capturing image. it leaves white space where the image occurs.

function capture()
{
    html2canvas(document.body, {
        allowTaint: true,
        logging:true,
        onrendered: function(canvas) {
        imagestring = canvas.toDataURL("image/png");
        console.log(imagestring);
        document.body.appendChild(canvas);
        }
    });
}

I have tried a lot but i cannot find solution .

Help is appreciated :)


Source: (StackOverflow)

On render in Html2Canvas, the page is scrolled to the top

I am using the html2canvas library, using the following code:

html2canvas(document.body, {
   onrendered: function(canvas) {
      document.body.appendChild(canvas);
   }
});

When onrendered is fired, the page is automatically scrolled to the top. Is there anyway we can maintain our scroll position and not be automatically taken to the top of the page?


Source: (StackOverflow)

html2canvas Tutorial? [closed]

I'd like to use html2canvas but I have no idea how.

No offense to Hertzen, he's made a great script, but the documentation is incomplete so it's rather useless.

I looked at JSFeedback but the whole script (which I had to 'steal' from the HTML source) works only with his version of html2canvas which, in the comments, he says is unready for open-sourceness.

Any help will be truly appreciated - Apparatix.


Source: (StackOverflow)

html2canvas screenshot of external website

I don't have even any idea how to do this and the documentation of html2canvas is not really helpful at this part.

I'm able to make a screenshot of my html with this little piece of code:

target = $('#myDiv');
        html2canvas( target, {
        onrendered: function( canvas ) {
            /* canvas is the actual canvas element, 
               to append it to the page call for example 
             */
               document.body.appendChild( canvas );
            }
        })

but i want to be able to pass an url and make a screenshot of this page. Like they do in their example page on: http://html2canvas.hertzen.com/screenshots.html

If anyone could give me a hint how to get started with that, I would be really glad.


Source: (StackOverflow)

How to save html2canvas image into System Folder in jquery

I have a form with id="form1" inside this form i have a graph.Now i am using html2canvas to get the image of this form1.Here is my code..

<script type="text/javascript">

      $(document).ready(function () {
          $('#add_button').click(function () {
              alert("hiii");
              $('form1').html2canvas();
              var queue = html2canvas.Parse();
              var canvas = html2canvas.Renderer(queue, { elements: { length: 1} });
              var img = canvas.toDataURL();
              window.open(img);
              alert("Hello");
          });
      });

  </script>

<form id="form1" runat="server">
<div style="padding-left:150px">
  <asp:Literal ID="FCLiteral1" runat="server"></asp:Literal>
</div>
<div style="padding-left:350px"><b>Demo</b></div>
</form>

 <input type="submit" id="add_button" value="Take Screenshot Of Div" " />

So my question is how can i save this image into my system hardisk..Please help me.


Source: (StackOverflow)

Arabic Encoding with html2canvas

I am using html2canvas to take an image of a div, the content is from the same page, same domain, but it shows the Arabic letters disconnected, it seems that html2canvas doesn't support Arabic.

While I am reading the available details about it on its webpage, I didn't find any useful information.

Here is the simple code I used:

$("#import").click(function(){
    // send the contents of the email :)
    html2canvas(document.body, {
        onrendered: function(canvas) {
            document.body.appendChild(canvas);
        },
        letterRendering:true
    });
});

how html2canvas renders the div

any clue?


Source: (StackOverflow)

Three.js Screenshot

I need to make screenshot of website. I tried using html2canvas and all and it's working. But problem is i'm using THREE.WebGLRenderer and THREE.CSS3DRenderer (for html in webgl)... So when I make screenshot it makes images only from WebGLRenderer. CSS3DRenderer is ignored and I don't know how to make screenshot image from both renderers. I'm using this solution: Take screenshot of <body> with html2canvas and store img as JS var


Source: (StackOverflow)

Google Map screen capture is not working for marker and marker cluster using html2canvas

I am doing python project using flask where I used google map api to show the map in the project. I implement html2canvas script to capture the map successfully. But I have marker too in the map which it is not capturing. So I tried using html2canvasPythonProxy Here is my snippet of javascript file of template gpsDataMap:

$(window).load(function(){
      $('#saveMap').click(function(){
          html2canvas(document.getElementById('map'), {
             "logging": true, //Enable log (use Web Console for get Errors and Warnings)
             "proxy":"/surveyApp/gpsDataMap/html2canvas-proxy",
             useCORS:true,
             "onrendered": function(canvas) {
              var img = new Image();
             img.onload = function() {
             img.onload = null;
             document.body.appendChild(img);
           };
            img.onerror = function() {
            img.onerror = null;
            if(window.console.log) {
               window.console.log("Not loaded image from canvas.toDataURL");
                  } else {
            alert("Not loaded image from canvas.toDataURL");
               }
              };
                img.src = canvas.toDataURL("image/png");
               }
            });

        });
    });

And My snippet of python code:

import os
import datetime

from flask import Flask, request, render_template, redirect, url_for, flash, Response
from flask.json import dumps
from flask import json
from flask import g, Blueprint, session, abort
from flask_principal import Identity, identity_changed, identity_loaded, RoleNeed, AnonymousIdentity
from flask_login import LoginManager, login_user, login_required, logout_user
from app import app
from model.user_info import SurveyForms

from flask.ext.pymongo import PyMongo

from inspect import getmembers, isfunction
import formConfig
import formTree
import fieldChoices
from dashboard import dashboardData
from collections import namedtuple
from pymongo import MongoClient
from flask import request


from html2canvasproxy import * #include html2canvasproxy in your application
import urlparse
import re




surveyApp_module = Blueprint('surveyApp_module', __name__)


app.config['MONGO_HOST'] = 'localhost'
app.config['MONGO_PORT'] = 27017
app.config['MONGO_DBNAME'] = 'survey'
mongo = PyMongo(app)

h2c = None
real_path = os.getcwd() + '/static/images'
virtual_path = '/gpsDataMap/images/'

@surveyApp_module.route('/')
@login_required
def show_formList():
    forms = []
    forms = [form.form_name for form in SurveyForms.select().where(SurveyForms.organization_name==session['organization_id'])]
    # strip .xml from string to compare with returnData
    forms =  [form.replace('.xml','') for form in forms]
    returnData = mongo.db.collection_names()
    returnData.pop(returnData.index('system.indexes'))
    intersected_forms = list(set(forms).intersection(returnData))
    if len(intersected_forms):
        return render_template('index_pjj.html', surveyEntries=intersected_forms)
    return render_template('index_pjj.html', surveyEntries=['No Survey'])

@surveyApp_module.route('/dashboard', methods=['POST'])
def dashboard():
    formName = request.form['whichSurvey']
    session['formName'] = formName
    formtree = formTree.formParseDict(formName)
    returnData = dashboardData(formName, mongo.db)
    summaryData = totalSummary(formName, mongo.db)
    jsonData = json.dumps(returnData)
    return render_template('dashboard.html', formName=formName, formTree=formtree, returnData=returnData, summaryData=summaryData, jsonData=jsonData)


@surveyApp_module.route('/gpsDataView', methods=['POST'])
def gpsDataView():
    formName = request.form['whichSurvey']
    gpsFields = formConfig.survey[formName]['gpsField']
    (location, fieldName, fieldSelection, fieldChoicesList) = "", "", "", []
    location = request.form['location']
    fieldName = request.form['fieldName']
    try:
        fieldSelection = request.form['fieldChoices']
    except KeyError:
        pass
    fieldChoicesList = request.form.getlist('fieldChoicesList')
    fieldData = commonFunctions.vizFieldList(formName)
    totalFieldData = commonFunctions.vizFieldListFull(formName)
    locationIdentifiers = fieldChoices.locationFieldChoices(formName, mongo.db)
    returnData = gpsVariate.getDataforGPSMap(formName, mongo.db, gpsFields, location, fieldName, fieldSelection, fieldChoicesList)
    return render_template('gpsDataMap.html', returnData=returnData, formName=formName, fieldData=fieldData, totalFieldData=totalFieldData, locationIdentifiers=locationIdentifiers)



    #Copy html2canvas.js to static folder (If not use cdns)
@surveyApp_module.route('/gpsDataMap/html2canvas.js')
def html2canvas_js():
    return app.send_static_file('html2canvas.js')



@surveyApp_module.route('/gpsDataMap/html2canvas-proxy')
def html2canvas_proxy():
    print ("is this proxy really calling ");
    h2c = html2canvasproxy(request.args.get('callback'), request.args.get('url'))
    h2c.userAgent(request.headers['user_agent'])
    # import pdb;pdb.set_trace()


    if request.referrer is not None:
        h2c.referer(request.referrer)

    h2c.route(real_path, virtual_path)

    r = h2c.result()
    # print r['mime']
    # print r['data']

    return Response(r['data'], mimetype=r['mime'])




 # Get images saved by html2canvasproxy
@surveyApp_module.route('/gpsDataMap/html2canvas/images/<image>')
def images(image):
    res = html2canvasproxy.resource(real_path, image)

    if res is None:
        return '', 404

    else:
        return res['data']

Here is my main.py script:

from app import app, db


from auth import *
from admin import admin
from model import *
from view import *
from filters.user_privilege import check_privilege
from filters.form_filter import filter_type

# custom filters
app.jinja_env.filters['check_privilege'] = check_privilege
app.jinja_env.filters['filter_type'] = filter_type


from surveyApp import surveyApp_module
app.register_blueprint(surveyApp_module, url_prefix='/surveyApp')

from view.accounts.login import login_module
app.register_blueprint(login_module)


if __name__ == '__main__':
    app.run(port=5555)

While doing so I get the following things in my console:

html2canvas: Preload starts: finding background-images html2canvas.js:21
html2canvas: Preload: Finding images html2canvas.js:21
html2canvas: Preload: Done. html2canvas.js:21
html2canvas: start: images: 1 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 2 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 3 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 4 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 5 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 6 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 7 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 8 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 9 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 10 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 11 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 12 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 13 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 14 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 15 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 16 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 17 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 18 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 19 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 20 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 21 / 23 (failed: 0) html2canvas.js:21
html2canvas: start: images: 22 / 23 (failed: 0) html2canvas.js:21
GET http://127.0.0.1:5555/home/bhim/app/surveyApp_bhim/images/a0af53c02bd2f2aed37f1d895edcf3485117c512.png 404 (NOT FOUND) html2canvas.js:2249
html2canvas: start: images: 23 / 23 (failed: 1) html2canvas.js:21
Finished loading images: # 23 (failed: 1) html2canvas.js:21
html2canvas: Error loading background: html2canvas.js:21
html2canvas: Renderer: Canvas renderer done - returning canvas obj 

UPDATED: The debugger result:

folder => images,
timeout => 30,
mimetype => application/javascript,
ua => Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:29.0) Gecko/20100101 Firefox/29.0,
host => 127.0.0.1:5555,
scheme => http,
ref => ,
url => http://www.google.com,
callback => console.log,
default_callback => console.log,
status => 0,
routePath => /static/images/,
savePath => /home/bhim/app/surveyApp_bhim/static/images/,
prefix => htc_,
real_extension => ,
mimes => ['image/bmp', 'image/windows-bmp', 'image/ms-bmp', 'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'text/html', 'application/xhtml', 'application/xhtml+xml']

UPDATED Screenshot of the images of google map

Google Map view that need to be capture ScreenShot of Map by html2canvaspythonproxy The marker is not being captured.


Source: (StackOverflow)