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.
Related
I'm trying to load an image from an external URL. The image is retrieved dynamically from a database and is therefore not a direct path. An example of such URL is: http://192.192.168.12:8080/api/imageServer?file=imageName.jpeg. The response in an actual jpeg image; when I add the URL to an image tag or directly in the browser the image is shown. When I try to load the image into Fabric.js I only get the console message "Error loading " without any other message.
This is part of our code:
var updateCanvas = function () {
self.canvas.clear();
if (self.selectedImage() && self.canvas) {
try {
fabric.Image.fromURL(self.selectedImage().imageUrl, function (oImg) {
if (oImg._element == null) {
stickyToast(translations().Error, translations().img_bind_error, "error");
return;
}
self.canvas.clear();
var canvasHeight = 500;
var ratio = canvasHeight / oImg.height;
var canvasWidth = oImg.width * ratio;
//Define all filters that will be used on image
oImg.filters[0] = new fabric.Image.filters.Brightness({
brightness: 0
});
...
I've tried upgrading to the latest version of fabric.js but to no avail. Is there another method I need to use download the image?
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 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!
For some reason that I can't understand, the html2canvas is not capturing the whole height of the div.
html2canvas($container, {
height: $container.height(),
onrendered: function(canvas) {
var data = canvas.toDataURL('image/png');
var file = dataURLtoBlob(data);
var formObjects = new FormData();
formObjects.append('file', file);
$.ajax({
url: 'ajax_preview',
type: 'POST',
data: formObjects,
processData: false,
contentType: false,
}).done(function(response){
console.log(response);
//window.open(response, '_blank');
});
}
});
I have also tried to set up the Height manually height: $container.height() but unfortunately the image keeps getting cut off. I also tried to set the height 1124, but the result is the same.
It's hard to see, but in the image below you see a white portion of the image without any border. Everything I have in that portion is not shown.
Any ideas of what could cause this behavior?
Solved.
My code is actually right, the problem was on a CSS file that I use.
To avoid this I've deleted and call again the file while converting the div into an image.
// $= means that ends with
("link[href$='my.css']").remove();
html2canvas($container, {
onrendered: function(canvas) {
var data = canvas.toDataURL('image/png');
var file = dataURLtoBlob(data);
// etc
$('head').append("<link href='" + base_url + "public/css/my.css' rel='stylesheet'/>");
}
});
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,