I need to convert my div in image or base64 using JS.
I found the html2canvas library on the Internet that performs this procedure, but always displays the error:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
When I add the element "canvas" it shows no error, but does not generate the base64 and neither image
I did the code with and without the canvas, Find the code below.
With Canvas
<script type="text/javascript">
var canvas = document.createElement('canvas');
var map = document.getElementById("mapa");
canvas.appendChild(map);
html2canvas(canvas, {
useCORS: true,
onrendered: function(canvas) {
var dataUrl= canvas.toDataURL("image/png");
console.log("Imagem - dataurl",dataUrl);
var encodedPng = dataUrl.substr(dataUrl.indexOf(',') + 1, dataUrl.length);
var decodedPng = Base64Binary.decode(encodedPng);
}});
Without Canvas
<script type="text/javascript">
var canvas = document.getElementById("mapa");
html2canvas(canvas, {
useCORS: true,
onrendered: function(canvas) {
var dataUrl= canvas.toDataURL("image/png");
console.log("Imagem - dataurl",dataUrl);
var encodedPng = dataUrl.substr(dataUrl.indexOf(',') + 1, dataUrl.length);
var decodedPng = Base64Binary.decode(encodedPng);
}});
I appreciate any help, as it already does not know what to do to accomplish this task!
Tks,
Related
I am converting the whole page into canvas, now I want to convert it into an image that I can download:
html2canvas(document.body, {
allowTaint: true,
onrendered: function(canvas) {
document.body.appendChild(canvas).setAttribute("id", "canvas");
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
img.setAttribute('crossOrigin', 'anonymous');
document.write('<img src="'+img+'"/>');
}
});
That works but I get this error in console and the image isn't created
Uncaught (in promise) DOMException: Failed to execute 'toDataURL' on
'HTMLCanvasElement': Tainted canvases may not be exported.
Try this:
<a id="download"
onclick="var download = document.getElementById('download');
download.href = document.getElementById('canvasElementId').toDataURL();
download.download='imageName.png'">
Save Canvas Image</a>
You had all that excess stuff you didn't need and it would generate an image that you have to do an extra step by right clicking and saving. This is way easier and works better.
If it has an error saying that "tainted canvases can't be exported", then you could remove the taint if it doesn't work and if you can be able to with your application.
If you can post the image data to a php script, it is very simple.
Posting data to php:
var imgData = canvas.toDataURL('image/png');
$.post("https://path-to-your-script/capture.php", {image: imgData},
function(data) {
console.log('posted');
});
Collecting data in php script:
capture.php
$data = $_POST['image'];
// remove "data:image/png;base64," from image data.
$data = str_replace("data:image/png;base64,", "", $data);
// save to file
file_put_contents("/tmp/image.png", base64_decode($data));
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
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.
I want open content toDataURL in src of modal bootstrap for preview image png
var dataURL = canvas.toDataURL({
format: 'png',
});
https://jsfiddle.net/gislef/k320kL4f/1/
I try:
<img src="data:">
That's pretty naive I know, but I am newbie in this matter
EDIT
tag img
<img src="" id="UrlCan">
javascript
var pngUrl = canvas.toDataURL();
document.getElementById("UrlCan").src = pngUrl ;
This returns blank image.
In console returns:
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAADICAYAAABS39xVAAAFz0lEQVR4Xu3UAQkAAAwCwdm/9HI83BLIOdw5AgQIRAQWySkmAQIEzmB5AgIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCE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ARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiDwGVgAyc5eaH0AAAAASUVORK5CYII="
https://jsfiddle.net/gislef/k320kL4f/2/
SOLUTION
$('viewt').onclick = function() {
var dataURL = canvas.toDataURL({
format: 'png'
});
document.getElementById("UrlCan").src = dataURL ;
};
In local host it work.
In fiddle doesn't working
Thanks for any help
You have 2 different problems here:
1) you have to make toDataUrl() from canvas when you click the preview button.
updatepreview = function() {
var pngUrl = canvas.toDataURL();
document.getElementById("UrlCan").src = pngUrl ;
}
$("#previw").click(updatepreview);
2) you have to set up the cross origin policy for your images. As of now adding images from that example taints the canvas. Once is tainted you cannot export to dataUrl anymore.
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!