Div to image with jQuery/JavaScript - javascript

I am trying to convert div to image using html2canvas library. I tried but no success can't convert full div to image, the dropper is missing in image.
URL: https://www.makethatvape.com/ejuicecalc/
Tried with code:
html2canvas($("#widget")).then(function(canvas) {
bimg = canvas.toDataURL(); // by default png
});
So, any idea how to overcome this problem. I played with html2canvas and it work for text and CSS div to canvas conversion.

Try this
<div id="copyDiv"></div>
var element = $("#widget"); // global variable
var getCanvas; // global variable
html2canvas(element, {
onrendered: function (canvas) {
$("#copyDiv").append(canvas);
getCanvas = canvas;
}
});
Note: If HTML markup contains an image tag, then for some browsers the above code will not be able to create the image of it. To make this work you need to use 2 parameters i.e. allowTaint, useCORS
Sample code :
html2canvas(document.getElementById("html-content-holder"), {
allowTaint: true, useCORS: true
}).then(function (canvas) {
var anchorTag = document.createElement("a");
document.body.appendChild(anchorTag);
document.getElementById("previewImg").appendChild(canvas);
anchorTag.download = "filename.jpg";
anchorTag.href = canvas.toDataURL();
anchorTag.target = '_blank';
anchorTag.click();
});
Detail Article: Convert HTML to image using jQuery / Javascript with live demos

Simpler way to do it:
var convertMeToImg = $('#myDiv')[0];
html2canvas(convertMeToImg).then(function(canvas) {
$('#resultsDiv').append(canvas);
});
https://html2canvas.hertzen.com/getting-started

Related

html2canvas - IndexSizeError

I am trying to take an image that is loaded into a div on my page and try and either pass in the raw data fro the image, or try and copy the image to a location.
The best method i could find was using html2canvas
I am getting the following error when trying to open my image into a window to preview:
JavaScript runtime error: IndexSizeError
I have read a few posts advising that i could render the div using the following method:
html2canvas($("#mapDiv"), {
onrendered: function (canvas) {
// canvas is the final rendered <canvas> element
var imgData = canvas.GetContext("2d").getImageData(bounds.left, bounds.top, bounds.width, bounds.height);
var myImage = imgData.toDataURL("image/png");
window.open(myImage);
}
});
The problem is occuring on the following line in the html2canvas js file
ctx.drawImage(canvas, bounds.left, bounds.top, bounds.width, bounds.height, 0, 0, bounds.width, bounds.height);
Is it possible to render an image that is dynamically loaded into a div in this way, as i cant pass in the pixel parameters due to users having different resolutions
and if it is possible, what am i doing wrong?
function capture(id) {
html2canvas([document.getElementById(id)], {
logging: true,
onrendered: function(canvas) {
document.body.appendChild(canvas);
var dataUrl = canvas.toDataURL("image/png")
//console.log(dataUrl)
$('#img-out').attr("src", canvas.toDataURL("image/png"));
$.post("/upload-img", {img: dataUrl, name: id}, function (res) {
console.log(res)
location.href = $("#" + id).attr("shareUrl") + "&picture=" + (window.location.protocol + "//" +window.location.host + "/" + res.filePath)
} )
}
});
}
pass id of element you want snapshot.

Convert Canvas to image then download

I am trying to convert a section of my site into a downloadable image.
Firstly I convert the html to a canvas using:
$(function() {
$("#download").click(function() {
html2canvas($("#the-grid"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
$("#saved").append(canvas);
$("#saved canvas").attr('id', 'scan');
}
});
Which works fine the canvas get generated and all look's good.
I then want to turn that into an image which I can use for thumbnails later but also initiate a download of the image.
To do so I complete the function like this.
$(function() {
$("#download").click(function() {
html2canvas($("#the-grid"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
$("#saved").append(canvas);
$("#saved canvas").attr('id', 'scan');
var c=document.getElementById("scan");
var d=c.toDataURL("image/png");
var w=window.open('about:blank','Download Mix');
w.document.write("<img src='"+d+"' alt='Custom Blend'/>");
}
});
But it doesn't work.
The error's I get are totally irrelevant.
I am an experienced developer but I'm pretty new to Jquery so any help would be appreciated.
UPDATE
Got it to work.
Create image like this
$(function () {
$("#download").click(function () {
html2canvas($("#the-grid"), {
onrendered: function (canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
$("#saved").append(canvas);
$("#saved canvas").attr('id', 'scan');
var image = canvas.toDataURL("image/png");
$("#saved").append("<img src='"+image+"' alt='Custom Blend'/>");
}
});
image html ends up looking like
<img src="data:image/png;base64,iVBORw0KGgoAAAANS..." alt="Custom Blend">
Maybe this can help you :
var image = canvas.toDataURL("image/png"); // build url of the image
window.location.href=image; //activate download
image = "<img src='"+image+"'/>"; // set canvas image as source
Here's how I did this (note, there's no way to download a file in Safari and set the filename without pinging a server):
First, you need to get the canvas as a png: var img = canvas.toDataUrl('image/png');
Then, you'll want to convert that dataURL to a blob. For a good way to do that, see this function.
Now you want to download that blob. This will work in all browsers but Safari:
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob, 'image.png');
} else {
var url = window.URL || window.webkitURL;
var objectURL = url.createObjectURL(blob);
var ele = $('<a target="_blank"></a>')
.hide()
.attr('download', 'image.png')
.attr('href', objectURL);
$('body').append(ele);
var clickEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false,
});
ele[0].dispatchEvent(clickEvent);
window.setTimeout(function() {
url.revokeObjectURL(objectURL);
ele.remove();
}, 1000);
}
This creates an invisible link and simulates a click on it. The click() function won't work in Firefox, so you have to create an event and dispatch it by hand. Finally, it does a bit of clean up by removing the invisible link after one second. In IE, it uses the method provided by Microsoft. This will download the image with the filename "image.png". It also has the benefit of being able to download any blob, if you need to be able to do more with your code. Hopefully this helps!

Change image size without losing quality via html2canvas

I take screenshot of the div via html2canvas. I want to change the size of caption div but without losing quality.
Here is my code example:
$(".meme-submit").on('click',(function() {
html2canvas($(".meme-img-upload"), {
onrendered: function(canvas) {
var extra_canvas = document.createElement("canvas");
extra_canvas.setAttribute('width',canvas.width*3);
extra_canvas.setAttribute('height',canvas.height*3);
var ctx = extra_canvas.getContext('2d');
ctx.drawImage(canvas,0,0,canvas.width, canvas.height,0,0,canvas.width*3,canvas.height*3);
$("#img_val").val(extra_canvas.toDataURL("image/png"));
document.getElementById("upload-meme").submit();
}
});
}));
Is someone have idea?

save image with text as a image to photo gallery in javascript

I have a temporary image which i want to copy to gallery using javascript(phonegap).
Any help?
function save() {
var image = document.getElementById("tempImg");
//upload image to gallery of mobile . But how??
}
My image contains photo and text together...
i just want to arrange all div data including image inside div with some text on it and save it as an full image with any format .jpg,png etc in javascript.
I referred this link but that is for canvas to image but i want div to image .
Canvas to PhotoLibrary [Phonegap]
You might want to check out this url: http://html2canvas.hertzen.com/.
Using this script, you can convert your div into a canvas, then use the "Canvas to PhotoLibrary [Phonegap]" to do the rest.
Your code would look something like this:
function save() {
var image = document.getElementById("tempImg");
html2canvas(image, {
onrendered: function(canvas) {
// use "Canvas to PhotoLibrary [Phonegap]" on the canvas variable
}
});
}
you save this using session storage(or)local storage
save:
var z1,z2,z3;
function save() {
var a=$("#theme1_text").val();
var b=$("#image_div").css("background-image");
var c=$("#background_theme1").css("background-image");
sessionStorage.z1=a;
sessionStorage.z2=b;
sessionStorage.z3=c;
};
view:
function view() {
$("#theme1_text").val(sessionStorage.z1);
$("#image_div").css("background-image",sessionStorage.z2);
$("#background_theme1").css("background-image",sessionStorage.z3);
};

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 =)
You should use it this way:
$('body').html2canvas();
var queue = html2canvas.Parse();
var canvas = html2canvas.Renderer(queue,{elements:{length:1}});
var img = canvas.toDataURL();
window.open(img);
It took me few hours to figure it out, how to use it the right way.
The {elements:{length:1}} is required, due to incomplete implementation of the plugin, otherwise you'll get an error.
Good luck!
You could also use the following:
var html2obj = html2canvas($('body'));
var queue = html2obj.parse();
var canvas = html2obj.render(queue);
var img = canvas.toDataURL();
window.open(img);
To just get a part of the page you can use it this way:
$('#map').html2canvas({
onrendered: function( canvas ) {
var img = canvas.toDataURL()
window.open(img);
}
This is what worked for me.
html2canvas(document.body, {
onrendered: function(canvas) {
var img = canvas.toDataURL()
window.open(img);
}
});
This created a new window for the screenshot.
I only wanted a portion of my page in the screenshot, specifically a container div. So I did the following:
html2canvas($('#myDiv'), {
onrendered: function(canvas) {
var img = canvas.toDataURL()
window.open(img);
}
});
For people looking up the same question, if the above options don't help, hopefully this will.
You can use the following code to capture a screenshot and download the screenshot.
html button creation
<button class="btn btn-default btn-sm" style="margin:0px 0px -10px 970px; padding:2px 4px 1px 4px" onclick="genScreenshot()"><span class="glyphicon glyphicon-envelope"></span></button>
<a id="test"></a>
<div id="box1"></div>
function definition
<script type="text/javascript">
function genScreenshot() {
html2canvas(document.body, {
onrendered: function(canvas) {
$('#box1').html("");
if (navigator.userAgent.indexOf("MSIE ") > 0 ||
navigator.userAgent.match(/Trident.*rv\:11\./))
{
var blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob,'Test file.png');
}
else {
$('#test').attr('href', canvas.toDataURL("image/png"));
$('#test').attr('download','screenshot.png');
$('#test')[0].click();
}
}
});
}
</script>
note: I have created a html button where I have called the function. test is an attribute and box1 is to get the canvas elements.
I have try this way and it working fine for me, you can try this one also.
https://github.com/vijayowork/screenshot-of-div-using-javascript.
I using domtoimage method.

Categories