html2canvas doesn't get image full height - javascript

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'/>");
}
});

Related

How to fix IE error when save photo edited with Konva?

I am trying to make a photo editor, do add some squares on images with Konva JS. I was able to get things done for all the browsers, but unfortunately IE cannot figure out. When I'm trying to save edited image, seems like it ignore everything from Konva (the squares) and more than that is stretching the image. I've asked a Konva moderator if has support for IE, and he told me that the library has compatibility with IE.
The app is made in Laravel and the request for saving is sent in controller by Ajax
Javascript:
function saveInCanvas () {
destroyTransformer();
destroyPreview();
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
var keyFrameId = $('#current-frame').attr('attr');
destroyTransformer();
dataURL = getCanvas.toDataURL();
$.ajax({
type: "POST",
url: "{{ route('save_debrand') }}",
data: {
survey_id: {{ $survey->id }},
imgBase64: dataURL,
keyFrameId: keyFrameId,
_token: "{{ csrf_token() }}",
},
success: function(response){
debrandingPreviousNextImage("imageSaved");
}
});
}
});
};
Controller:
public function ajxSaveEdited(Request $request){
$image = Image::make($request->get('imgBase64'));
$filename = uniqid().'.jpg' ;
$file = public_path('storage/surveys/'.$filename);
$image->save($file);
}
Does IE has something particular for getting image from canvas?
Thank you!
I've solved the problem, I just applied an z-index for the canvas which is dynamically appended to the div (this is the way Konva creates canvas)

Javascript: Pass created image through ajax.

So I created an image using canvas. And I want to pass the image using ajax. I know how to do it using form but this time I'm not using one. This is my code for creating image.
var video = document.querySelector('video')
, canvas;
var img = document.querySelector('img') || document.createElement('img');
var context;
var width = video.offsetWidth
, height = video.offsetHeight;
canvas = canvas || document.createElement('canvas');
canvas.width = width;
canvas.height = height;
context = canvas.getContext('2d');
context.drawImage(video, 0, 0, width, height);
img.src = canvas.toDataURL('image/png');
document.body.appendChild(img);
the "img" variable is my created image. This is my code of passing image using ajax
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/api/file/upload",
data: data,
processData: false, //prevent jQuery from automatically transforming the data into a query string
contentType: false,
cache: false,
success: (data) => {
$("#listFiles").text(data);
},
error: (e) => {
$("#listFiles").text(e.responseText);
}
});
I tried other tutorials by creating a new FormData but it doesn't seem to work. I also tried assigning value to input file type.But it doesn't work and others doesn't recommend it due to future security problems. Hoping you could help me.

How to fix image size posted to server using Javascript Cropper

I'm using Cropper https://github.com/fengyuanchen/cropper in a content management system but I'm struggling to get it to fix the size of a cropped image.
What I want to do is ensure whatever size of crop box is drawn on the canvas also results in a cropped image size of exactly 560px X 420px being passed through to the webserver.
The iQuery code I have at the moment is:-
$("#accept_crop").click(function() {
var $image = $("#image");
var cropper = $image.cropper();
var baseURL = window.location.protocol+'//'+window.location.host;
var pho_id = $("input[name=pho_id]").val();
var mem_id = $("input[name=mem_id]").val();
var photopath = $("input[name=photopath]").val();
$image.cropper('getCroppedCanvas').toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
formData.append('pho_id', pho_id);
formData.append('mem_id', mem_id);
formData.append('photopath', photopath);
$.ajax(baseURL+'/path', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
}, 'image/jpeg', 0.8);
});
The cropped image is passing over fine but always results in a variable size depending on the size of the crop box that's drawn. Is there any way of fixing the size on the client site regardless of the crop box so that the image is scaled up or down, without using PHP to re-scale it?
This always seems to happen... As soon as I've posted a question, I usually answer it myself shortly afterwards even though I've already spent ages trying to figure it out.
By adding adding the width and height options, this seems to work:-
$image.cropper('getCroppedCanvas', {'width': 560, 'height': 420}).toBlob(function (blob) {
It can be done, check its documentation:
https://github.com/fengyuanchen/cropper#getcroppedcanvasoptions
You can set destination width and height of the output canvas.
Other thing is you need to set the proportion ration as per your required width and height. 560/420 is proportional to 4/3. Set aspectRatio: 4/3. Which will resize the image to your desired size without compromising anything.

Div to image with jQuery/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

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.

Categories