HTML2Canvas works on desktop but not on mobile. How to fix? - javascript

The point of the website is to download an image of a signed consent form. Everything works how I would like on desktop, but it does not work on mobile unfortunately. I tried chrome, brave, firefox, and safari. I either get the image showing but not downloading, or some weird page distortion. How can I adjust the code to fix it?
this is the source code:
https://github.com/jacelecomte/wwvhSigns
The methods that deal with the saving of the image are here:
function finalizeScreenshot() {
html2canvas(document.body).then(function (canvas) {
document.body.appendChild(canvas);
saveScreenshot(canvas);
});
}
function injectScript(uri) {
const document = window.document;
const script = document.createElement("script");
script.setAttribute("src", uri);
//document.body.appendChild(script);
}
function injectHtml2canvas() {
injectScript("//html2canvas.hertzen.com/dist/html2canvas.js");
}
injectScript('./src/html2canvas.js');
injectHtml2canvas();
finalizeScreenshot();
function saveScreenshot(canvas) {
const fileName = "Consent Form";
const link = document.createElement("a");
link.download = fileName + ".png";
//console.log(canvas);
canvas.toBlob(function (blob) {
console.log(blob);
link.href = URL.createObjectURL(blob);
link.click();
});
}
//these 3 functions are run in a row to create and download the screenshot.
injectScript('./src/html2canvas.js');
injectHtml2canvas();
finalizeScreenshot();

Change the viewport just before calling html2canvas, then change it back afterwards. This answer was derived from html2canvas issue fix on github
This should fix it:
1: give your <meta name="viewport"../> an id, like this:
<meta name="viewport" content="width=device-width, initial-scale=1.0" id="viewportMeta" />
revised function
function finalizeScreenshot() {
var vp = document.getElementById("viewportMeta").getAttribute("content");
document.getElementById("viewportMeta").setAttribute("content", "width=800");
html2canvas(document.body).then(function (canvas) {
document.body.appendChild(canvas);
saveScreenshot(canvas);
}).then(function () {
document.getElementById("viewportMeta").setAttribute("content", vp);
}); }

You should also be able to set your own windowWidth setting which should trigger the relevant media queries:
html2canvas( document.body, {
windowWidth: '1280px'
} ).then( function( canvas ) {
document.body.appendChild( canvas );
} );
See the available html2canvas options.

Related

chart js download to png with canvas.toDataURL() not working in IE and firefox

I am using canvas.toDataURL() to download chart.js chart ,it is perfectly working with chrome but not working with IE and Firefox.here is my code
var link = document.createElement('a');
var canvas = document.getElementById('canvasId');
link.href = canvas.toDataURL("image/png");
link.download = 'IMAGE.png';
link.click();
Thank you.
var canvas = document.getElementById('canvasId');
if(canvas.msToBlob){
var blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob, 'image.png');
}
else{
var link = document.createElement('a');
link.href = canvas.toDataURL("image/png");
link.download = 'IMAGE.png';
document.body.append(link);
link.click();
}
The anchor tag you are creating also needs to be added to the DOM in Firefox and IE, in order to be recognized for click events.
In Firefox, you need to do the link.click (though you may not want to do that in Chrome as it results in a double download). However, IE (except for the latest versions of Edge) doesn't support the "download" attribute on the a tag, and you need to save the canvas slightly differently.
var canvas = document.getElementById('canvasId');
var isIE = !!navigator.userAgent.match(/Trident/g) || !!navigator.userAgent.match(/MSIE/g);
if (!isIE) {
let image = canvas.toDataURL("image/jpeg", 1.0);
// we are getting the a tag to add the 'download' attribute and the file contents
let downloadLink = document.getElementById("download");
downloadLink.setAttribute("download", downloadFileName);
downloadLink.setAttribute("href", image);
// For some reason, we need to click the button again in firefox for the download to happen
if (navigator.userAgent.match(/Firefox/g)) {
downloadLink.click();
}
}
if (isIE) {
var blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob, downloadFileName);
}
In the Chart.js API documentation there is a built in function called .toBase64Image() which you may wish to use instead, as you've outlined your file extension as being .png.
As Becky stated above, in Firefox, link.click() needs to be used in order for the file to download. However, the element we created (link) needs to be appended to the body of your HTML document in order for link.click() to function as required. It is important that once this statement has been executed, to remove the link element from your HTML document, so your HTML body doesn't accumulate these elements every time you try to download a chart. IE requires the canvas to be saved differently through the blob functions.
let canvas = document.getElementById('canvasId');
let chart_name = = new Chart(canvas, config);
var isIE = !!navigator.userAgent.match(/Trident/g) || !!navigator.userAgent.match(/MSIE/g);
if (!isIE) {
// Create a hyperlink element.
let link = document.createElement('a');
// Set image URL and filename.
link.href = chart_name.toBase64Image();
link.download = 'IMAGE.png';
// If browser is Firefox, the element we created above must be appended to the
// body of the HTML document & therefore removed after.
if (navigator.userAgent.match(/Firefox/g)) {
document.body.append(link);
link.click();
document.body.removeChild(link);
}
}
if (isIE) {
var blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob, 'IMAGE.png');
}

Save high-res image html5/threejs-canvas

I found and edited below code to save my html5 canvas as a .png-image. The canvas is generated by Three.js/Potree.
This code works perfectly. But, I want a higher resolution image as an output. Usually, the THREEjs renderer is sized according to the clients browser size. I have already manually enlarged it to 3000x2000. This edit will give a higher-resolution image, but when increasing more no effects are visible anymore.
Is there a simple (I'm not that into javascript..) workaround for downloading a high-resolution output image?
At first, the images are just for me. No user needs to download it or needs to pass it onto the server. Although, if its a neat solution, I'd like to give the user the possibility to save their image as well.
function saveAsImage() {
var strDownloadMime = "image/octet-stream";
//alert("function saveimage")
var imgData, imgNode;
try {
var strMime = "image/png";
imgData = viewer.renderer.domElement.toDataURL(strMime);
saveFile(imgData.replace(strMime, strDownloadMime), "test.png");
} catch (e) {
console.log(e);
return;
}
}
var saveFile = function (strData, filename) {
//alert("savefilefunction");
var link = document.createElement('a');
if (typeof link.download === 'string') {
document.body.appendChild(link); //Firefox requires the link to be in the body
link.download = filename;
link.href = strData;
link.click();
document.body.removeChild(link); //remove the link when done
} else {
location.replace(uri);
}
}
THREE Renderer settings:
let width = 3000;
let height= 2000;
this.renderer = new THREE.WebGLRenderer({premultipliedAlpha: false, preserveDrawingBuffer: true});
this.renderer.setSize(width, height);

Error loading image through localforage blob on ios

I am grabbing camera image on an ios device through Cordova camera API and then saving it through localforage. However, it seems that the resource is not being loaded since clicking on the blob under Resources tag of Safari Web Inspector shows An error occured while trying to load resources error, and the image renders as 20x20 white background instead of photo. Here is my HTML wrapper around Cordova Camera API:
<head>
<title>Capture Photo</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/camera.js"></script>
<script type="text/javascript" charset="utf-u" src="js/localforage.js"></script>
<script type="text/javascript">
function savePhoto(contents){
localforage.setItem('photo', contents, function(img) {
// This will be a valid blob URI for an <img> tag.
var blob = new Blob([img], { type: "image/jpeg" } );
var imageURI = window.URL.createObjectURL(blob);
console.log(imageURI);
var newImg = document.createElement("img");
newImg.src=imageURI;
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newImg, currentDiv);
});
console.log(contents.byteLength);
}
function grabPhoto(){
capturePhotoEdit(savePhoto,function(e){console.log(e);});
}
</script>
</head>
<body>
<button onclick="grabPhoto();">Capture Photo</button> <br>
<div id="div1"> </div>
</body>
</html>
We use savePhoto to save down the image grabbed from the camera (in js/camera.js). Console logging of blob prints out stuff like blob:null/916d1852-c8c5-4b3b-ac8c-86b6c71d0e86.
I will very much appreciate pointers on what I am doing wrong here with image rendering.
Fixed now by switching to "Promise" style API. Somehow, it doesn't work for async callback API version. Fixed JS code below:
function savePhoto(contents){
localforage.setItem('photo', contents).then(function(image) {
// This will be a valid blob URI for an <img> tag.
var blob = new Blob([image],{ type:"image/jpeg" });
console.log('size=' + blob.size);
console.log('type=' + blob.type);
var imageURI = window.URL.createObjectURL(blob);
var newImg = document.createElement("img");
newImg.src=imageURI;
newImg.onload = function() {
URL.revokeObjectURL(imageUrI);
};
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newImg, currentDiv);
}).catch(function(err) {
// This code runs if there were any errors
console.log(err);
});
}
function grabPhoto(){
capturePhotoEdit(savePhoto,function(e){console.log(e);});
}

how to save a picture taken with window.getusermedia in js

Currently i am working on a open webapp camera, right now i have implemented the camera setup(live stream as viewport, take picture button, capture, display taken picture in corner... etc) but now i am running into the issue of how to save that picture for the user to their device or computer, this app is currently being designed for mobile b2g primarily. I know most people are gonna tell me security issues!!! i dont mean tell the device exactly where to put it. I mean something like
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript">
window.onload = function () {
var img = document.getElementById('embedImage');
var button = document.getElementById('saveImage');
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA'+
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO'+
'9TXL0Y4OHwAAAABJRU5ErkJggg==';
img.onload = function () {
button.removeAttribute('disabled');
};
button.onclick = function () {
window.location.href = img.src.replace('image/png', 'image/octet-stream');
};
};
</script>
</head>
<body>
<img id="embedImage" alt="Red dot"/>
<input id="saveImage" type="button" value="save image" disabled="disabled"/>
</body>
</html>
that specific code executed on mobile triggers the file to automatically be saved on click of the button. now what i want to do is use that to take my picture from its var its in and save it as that file, for example that will be in downloads folder.
this is what my code is currently https://github.com/1Jamie/1Jamie.github.io
any help would be appreciated and this is the current running implementation if you want to take a working look http://1Jamie.github.io
This worked for me when I was playing around with getUserMedia - I did notice that you did not have the name of the method in the proper case and it is a method of the navigator.mediaDevices interface - not a method of the window directly...
References:
[Navigator for mozilla]https://developer.mozilla.org/en-US/docs/Mozilla/B2G_OS/API/Navigator
https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices
[mediaDevices for chrome and android]https://developers.google.com/web/updates/2015/10/media-devices?hl=en
var video = document.getElementById('monitor');
var canvas1 = document.getElementById('photo1');
var img1 = document.getElementById('canvasImg');
navigator.mediaDevices.getUserMedia({
video: true
}).then(function (stream) {
video.srcObject = stream;
video.onloadedmetadata = function () {
canvas1.width = video.videoWidth;
canvas1.height = video.videoHeight;
document.getElementById('splash').hidden = true;
document.getElementById('app').hidden = false;
};
}).catch(function (reason) {
document.getElementById('errorMessage').textContent = 'No camera available.';
});
function snapshot1() {
canvas1.getContext('2d').drawImage(video, 0, 0);
}
"save_snap" is the id of a button - Disclaimer I am using jQuery- but you should easily see where this corresponds to your code:
$("#save_snap").click(function (event){
// save canvas image as data url (png format by default)
var dataURL = canvas2.toDataURL();
// set canvasImg image src to dataURL
// so it can be saved as an image
$('#canvasImg').attr("src" , dataURL);
$('#downloader').attr("download" , "download.png");
$('#downloader').attr("href" , dataURL);
//* trying to force download - jQuery trigger does not apply
//Use CustomEvent Vanilla js: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
// In particular
var event1 = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
//NOW we are effectively clicking the element with the href attribute:
//Could use jQuery selector but then we would have to unwrap it
// to expose it to the native js function...
document.getElementById('downloader').dispatchEvent(event1);
});

how to validate image size and dimensions before saving image in database

I am using ASP.NET C# 4.0, my web form consist of input type file to upload images.
i need to validate the image on client side, before saving it to my SQL database
since i am using input type= file to upload images, i do not want to post back the page for validating the image size, dimensions.
Needs your assistance
Thanks
you can do something like this...
You can do this on browsers that support the new File API from the W3C, using the readAsDataURL function on the FileReader interface and assigning the data URL to the src of an img (after which you can read the height and width of the image). Currently Firefox 3.6 supports the File API, and I think Chrome and Safari either already do or are about to.
So your logic during the transitional phase would be something like this:
Detect whether the browser supports the File API (which is easy: if (typeof window.FileReader === 'function')).
If it does, great, read the data locally and insert it in an image to find the dimensions.
If not, upload the file to the server (probably submitting the form from an iframe to avoid leaving the page), and then poll the server asking how big the image is (or just asking for the uploaded image, if you prefer).
Edit I've been meaning to work up an example of the File API for some time; here's one:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show Image Dimensions Locally</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function loadImage() {
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('imgfile');
if (!input) {
write("Um, couldn't find the imgfile element.");
}
else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = document.createElement('img');
img.onload = imageLoaded;
img.style.display = 'none'; // If you don't want it showing
img.src = fr.result;
document.body.appendChild(img);
}
function imageLoaded() {
write(img.width + "x" + img.height);
// This next bit removes the image, which is obviously optional -- perhaps you want
// to do something with it!
img.parentNode.removeChild(img);
img = undefined;
}
function write(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='imgfile'>
<input type='button' id='btnLoad' value='Load' onclick='loadImage();'>
</form>
</body>
</html>
Works great on Firefox 3.6. I avoided using any library there, so apologies for the attribute (DOM0) style event handlers and such.
function getImgSize(imgSrc) {
var newImg = new Image();
newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
alert ('The image size is '+width+'*'+height);
}
newImg.src = imgSrc; // this must be done AFTER setting onload
}

Categories

Resources