I'm trying to take a screen shot of a map that uses dash-leaflet. When the screen shot it taken with html2canvas, the overlay on the map is moved upward and to the left. I have been trying to correct this but the html2canvas documentation is pretty sparse, and I'm not sure what will correct the issue.
$(document).ready(function () {
$(document).on('click', "#btn-frame-download", function () {
var element = document.getElementById("graph-collection"); // global variable
if (element == null) {
element = document.getElementById("prob-graph"); // global variable
if (element == null) {
element = document.getElementById("was-graph"); // global variable
}
}
getCanvas(element);
});
});
function getCanvas(element) {
html2canvas(element, {
scrollX: 0,
scrollY: 0,
allowTaint: true,
useCORS: true,
async: false,
width: element.clientWidth,
height: element.clientHeight,
logging: true,
imageTimeout: 0,
}).then(function (canvas) {
saveAs(canvas.toDataURL(), 'image.png');
});
}
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
link.href = uri;
link.download = filename;
document.body.appendChild(link);
//simulate click
link.click();
//remove the link when done
document.body.removeChild(link);
} else {
window.open(uri);
}
}
download-img.js [+]
Original
Output by html2canvas
Above you can see the how the screen looks in it's original format, and then what is output by html2canvas. Any tips would be greatly appreciated.
Related
I am trying to add a custom transform control to geoman, to do certain transformations with polylines and polygons. I see that on edit, geoman draws hint lines above vertices etc. I would like my tool to highlight polylines/polygons with the same type of hints. Below is the skeleton of my action:
const ConvertAction = L.Toolbar2.Action.extend({
options: {
toolbarIcon: {
html:
'<div class="icon-maps icon-convert" title="Convert point"></div>',
tooltip: 'Convert point'
}
},
addHooks: () => {
// draw polygon
// map.pm.enableDraw();
changeConvert();
}
});
function changeConvert() {
convert = true;
map.eachLayer(function (layer) {
if (layer.feature && layer.feature.geometry.type === 'Point') {
layer._icon.style['pointer-events'] = 'auto';
}
});
}
Is there an internal function or something that I could use to outline shapes? When I enable Edit layers tool already built into the geoman, shapes are outlined for me. How could I achieve this from my code without having to reimplement the entire thing?
Thus far, after quickly reviewing geoman code, I was able to come up with:
const ConvertAction = L.Toolbar2.Action.extend({
options: {
toolbarIcon: {
html:
'<div class="icon-maps icon-convert" title="Convert point"></div>',
tooltip: 'Convert point'
}
},
addHooks: () => {
// draw polygon
// map.pm.enableDraw();
if (!convert) changeConvert();
else disableConvert();
}
});
function changeConvert() {
convert = true;
map.eachLayer(function (layer) {
if (
layer?.feature?.geometry.type === 'Polygon' ||
layer?.feature?.geometry.type === 'LineString'
) {
const coords = layer.getLatLngs();
const markerGroup = new L.LayerGroup();
markerGroup._pmTempLayer = true;
const createMarker = (latlng) => {
const marker = new L.Marker(latlng, {
draggable: true,
icon: L.divIcon({ className: 'marker-icon' })
});
layer.options.pane =
(map.pm.globalOptions.panes &&
map.pm.globalOptions.panes.vertexPane) ||
'markerPane';
marker._pmTempLayer = true;
markerGroup.addLayer(marker);
return marker;
};
const handleRing = (coordsArr) => {
// if there is another coords ring, go a level deep and do this again
if (Array.isArray(coordsArr[0])) {
return coordsArr.map(handleRing, this);
}
// the marker array, it includes only the markers of vertexes (no middle markers)
const ringArr = coordsArr.map(createMarker);
return ringArr;
};
const markers = handleRing(coords);
map.addLayer(markerGroup);
}
});
}
function disableConvert() {
convert = false;
map.eachLayer(function (layer) {
if (
layer.dragging &&
layer.options?.draggable === true &&
layer._pmTempLayer === true
) {
console.log('temp layer:', layer);
map.removeLayer(layer);
}
});
update();
}
Seems like an excessive amount of code, and reimplementation [and probably not as good the geoman version as I don't fully understand geoman code by far] of existing functionality.
How do I simplify/fix this?
Lines and polygons are added without problems, but when trying to add markers on top of a polygon layer ("lyrPoly"), it interprets that I want to click on the polygon (e.g. opens popup) instead of adding marker. How can I avoid this? I am using leaflet.pm to add markers, linestrings and polygons.
This is the code for the marker:
map.on('pm:create', function(e) {
e.marker;
var type = e.layerType,
layer = e.layer;
$(document).ready(function() {
var jsnMarker = layer.toGeoJSON().geometry;
jsnMarker = {
type: "MultiPoint",
coordinates: [jsnMarker.coordinates]
};
})
});
$(function() {
$('.check').change(function() {
var data = $(this).val();
if (data == "versionOne") {
var markerStyle = {
draggable: false,
icon: customIcon,
};
var options = {
markerStyle,
}
map.pm.enableDraw('Marker', options);
} else if (data == "versionTwo") {
var markerStyle = {
draggable: false,
icon: otherIcon,
};
var options = {
markerStyle,
}
map.pm.enableDraw('Marker', options);
}
$('.check').trigger('change');
});
And inside the ajax function I use this:
lyrMarker = L.geoJSON(jsnMarker, {
pointToLayer: function (feature, latlng) {
if(feature.properties.marker_type=="versionOne"){
return L.marker(latlng, {
icon: customIcon
})
}else if
(feature.properties.marker_type=="versionTwo"){
return L.marker(latlng, {
icon: otherIcon
})
} ,
onEachFeature: forEachMarker
});
For the polygon-layer I have a corresponding "onEachFeature"-function that looks like this:
function forEachFeature(feature, layer) {
var att = feature.properties;
var popupContent =
"Popup-content" ;
layer.bindPopup(popupContent, {
offset: [0, -120]
});
layer.on("click", function (e) {
lyrPoly.setStyle(style); //resets layer colors
layer.setStyle(highlight); //highlights selected.
});
};
Adding marker to the background/basemap works fine, but not onto the polygon layer. Why is that, and what would be a good solution? I don't want to add the marker to the same layer as the polygons, but avoid polygons "getting in the way".
I've had ideas about making the polygon layer interactive: false while in adding-marker-mode, but haven't succeeded.
Update your click event and test if drawing mode is enabled:
function forEachFeature(feature, layer) {
var att = feature.properties;
var popupContent =
"Popup-content" ;
layer.bindPopup(popupContent, {
offset: [0, -120]
});
layer.on("click", function (e) {
if(!map.pm.Draw.Marker.enabled()){
lyrPoly.setStyle(style); //resets layer colors
layer.setStyle(highlight); //highlights selected.
}
});
};
Update
To disable the popup open event add following code at the top of your file. Before you create a Layer with a Popup:
L.Layer.include({
_openPopup: function (e) {
var layer = e.layer || e.target;
//This IF is new
if(map.pm.Draw.Marker.enabled()){
return;
}
if (!this._popup) {
return;
}
if (!this._map) {
return;
}
// prevent map click
L.DomEvent.stop(e);
// if this inherits from Path its a vector and we can just
// open the popup at the new location
if (layer instanceof L.Path) {
this.openPopup(e.layer || e.target, e.latlng);
return;
}
// otherwise treat it like a marker and figure out
// if we should toggle it open/closed
if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
this.closePopup();
} else {
this.openPopup(layer, e.latlng);
}
},
});
Example: https://jsfiddle.net/falkedesign/dg4rpcqe/
I am using the Jquery file upload basic-plus.html. I am not sure How to use the Resumable uploading functionality in the below code.
I see something like this according to the documentation but not sure How to use that with the basic-plus.html
$('#fileupload').fileupload({
maxChunkSize: 10000000, // 10 MB
add: function (e, data) {
var that = this;
$.getJSON('server/php/', {file: data.files[0].name}, function (result) {
var file = result.file;
data.uploadedBytes = file && file.size;
$.blueimp.fileupload.prototype
.options.add.call(that, e, data);
});
}
});
I tried something like below. But didn't work.
basic-plus.html
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = window.location.hostname === 'blueimp.github.io' ?
'//jquery-file-upload.appspot.com/' : 'server/php/',
uploadButton = $('<button/>')
.addClass('btn btn-primary')
.prop('disabled', true)
.text('Processing...')
.on('click', function () {
var $this = $(this),
data = $this.data();
$.getJSON('server/php/', {file: data.files[0].name}, function (result) {
console.log('come here');
console.log(result);
var file = result.file;
data.uploadedBytes = file && file.size;
//$.blueimp.fileupload.prototype.options.add.call($this, data);
});
$this
.off('click')
.text('Abort')
.on('click', function () {
$this.remove();
data.abort();
});
data.submit().always(function () {
$this.remove();
});
});
$('#fileupload').fileupload({
url: url,
dataType: 'json',
autoUpload: false,
//multipart: false,
acceptFileTypes: /(\.|\/)(avi|flv|wmv|mpg|mp4|mov|3gp|m4v)$/i,
maxFileSize: 969932800, // 900 MB
maxChunkSize: 2000000, // 2 MB
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true,
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>').append($('<span/>').text(file.name));
console.log(node);
if (!index) {
node
.append('<br>')
.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append($('<span class="text-danger"/>').text(file.error));
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
I have a div that i want to screenshot and save,
here is my code
function _download(uri, filename)
{
var el = $('.sf-download-button');
if (el.length)
{
var link = document.createElement('a');
if (typeof link.download === 'string')
{
link.href = uri;
link.download = filename;
document.body.appendChild(link);
//simulate click // this causes page to download an empty html file not sure why
link.click();
//remove the link when done
document.body.removeChild(link);
}
else
{
window.open(uri);
}
}
}
function _save()
{
window.takeScreenShot = function ()
{
var a =document.getElementById("my-div");
html2canvas(document.getElementById("the-div-that-i-want-to-screenshot"), {
onrendered: function (canvas)
{
document.body.appendChild(canvas);
a.append(canvas);
},
width: 220,
height: 310
});
};
$("#btnSave2").click(function ()
{
html2canvas(document.getElementById("data"), {
onrendered: function (canvas)
{
_download_card(canvas.toDataURL(), 'save.png');
}
});
});
}
This is the code i got it from web and added some of my own stuff.code was working i believe but right now, when I click on the button show me the image, it creates the image i can see it but it is just blank.
I tried every possible code combination from jsfiddle and all that and couldn't get anything different as a result.
What could be going wrong here?
I solved the problem by simply changing the browser,
It was not working with Chrome but works perfectly on Mozilla.
Also i changed the code to this,
$("#btnSave").click(function() {
html2canvas($("#card"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
// Convert and download as image
$("#img-out").append(canvas);
// Clean up
//document.body.removeChild(canvas);
}
});
});
Works perfect on Mozilla only.
I wanna save some images from a site. At the moment I can get the paths to the images but I have no clue how to get and save the images with phantomJs.
findRotationTeaserImages = ->
paths = page.evaluate ->
jQuery('.rotate img').map(-> return this.src).get()
for path, i in paths
console.log(path);
//save the image
I know this is an old question, but you do this pretty simply by storing the dimensions and location of each image on the in an object, then altering the phantomjs page.clipRect so that the page.render() method renders only the area where the image is. Here is an example, scraping multiple images from http://dribbble.com/ :
var page = require('webpage').create();
page.open('http://dribbble.com/', function() {
page.includeJs('//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',function() {
var images = page.evaluate(function() {
var images = [];
function getImgDimensions($i) {
return {
top : $i.offset().top,
left : $i.offset().left,
width : $i.width(),
height : $i.height()
}
}
$('.dribbble-img img').each(function() {
var img = getImgDimensions($(this));
images.push(img);
});
return images;
});
images.forEach(function(imageObj, index, array){
page.clipRect = imageObj;
page.render('images/'+index+'.png')
});
phantom.exit();
});
});
There is now another way to do this.
var fs = require("fs");
var imageBase64 = page.evaluate(function(){
var canvas = document.createElement("canvas");
canvas.width =img.width;
canvas.height =img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
return canvas.toDataURL ("image/png").split(",")[1];
})
fs.write("file.png",atob(imageBase64),'wb');
Solve this by starting a child process running a node script that download the images:
phantomJs script:
findRotationTeaserImages = ->
paths = page.evaluate ->
jQuery('.rotate img').map(-> return this.src).get()
args = ('loadRotationTeaser.js ' + paths.join(' ')).split(' ')
child_process.execFile("node", args, null, (err, stdout, stderr) ->
phantom.exit()
)
nodeJs script
http = require('http-get');
args = process.argv.splice(2)
for path, i in args
http.get path, 'public/images/rotationTeaser/img' + i + '.jpeg', (error, result) ->
In case image dimensions are known:
var webPage = require('webpage');
/**
* Download image with known dimension.
* #param src Image source
* #param dest Destination full path
* #param width Image width
* #param height Image height
* #param timeout Operation timeout
* #param cbk Callback (optional)
* #param cbkParam Parameter to pass back to the callback (optional)
*/
function downloadImg(src, dest, width, height, timeout, cbk, cbkParam) {
var page = webPage.create();
page.settings.resourceTimeout = timeout; //resources loading timeout(ms)
page.settings.webSecurityEnabled = false; //Disable web security
page.settings.XSSAuditingEnabled = false; //Disable web security
page.open(src, function(status) {
// missing images sometime receive text from server
var success = status == 'success' && !page.plainText;
if (success) {
page.clipRect = {
top: 0,
left: 0,
width: width,
height: height
};
page.render(dest);
}
cbk && cbk(success, cbkParam);
page.close();
});
};
I've experienced really a lot troubles when using the render method. Luckily I finally come up with two better solution. Here is the code I used in my project. First solution has some trouble to update the cookie, so it cannot work well when fetching captcha image. Both method will cause a new http request. But with a few modifications, the second one can ommit such kind of request.
The first one fetches the cookie from phantomJs and makes a new http request using request. The second one uses base64 to pass the image.
async download(download_url, stream) {
logger.profile(`download(download_url='${download_url}')`);
let orig_url = await this.page.property('url');
download_url = url.resolve(orig_url, download_url);
let cookies = await this.page.property('cookies');
let jar = request.jar();
for (let cookie of cookies) {
if (cookie.name !== undefined) {
cookie.key = cookie.name;
delete cookie.name;
}
if (cookie.httponly !== undefined) {
cookie.httpOnly = cookie.httponly;
delete cookie.httponly;
}
if (cookie.expires !== undefined)
cookie.expires = new Date(cookie.expires);
jar.setCookie(new Cookie(cookie), download_url, {ignoreError: true});
}
let req = request({
url: download_url,
jar: jar,
headers: {
'User-Agent': this.user_agent,
'Referer': orig_url
}
});
await new Promise((resolve, reject) => {
req.pipe(stream)
.on('close', resolve)
.on('error', reject);
});
// Due to this issue https://github.com/ariya/phantomjs/issues/13409, we cannot set cookies back
// to browser. It is said to be redesigned, but till now (Mar 31 2017), no change has been made.
/*await Promise.all([
new Promise((resolve, reject) => {
req.on('response', () => {
jar._jar.store.getAllCookies((err, cookies) => {
if (err) {
reject(err);
return;
}
cookies = cookies.map(x => x.toJSON());
for (let cookie of cookies) {
if (cookie.key !== undefined) {
cookie.name = cookie.key;
delete cookie.key;
}
if (cookie.httpOnly !== undefined) {
cookie.httponly = cookie.httpOnly;
delete cookie.httpOnly;
}
if (cookie.expires instanceof Date) {
cookie.expires = cookie.expires.toGMTString();
cookie.expiry = cookie.expires.toTime();
}
else if (cookie.expires == Infinity)
delete cookie.expires;
delete cookie.lastAccessed;
delete cookie.creation;
delete cookie.hostOnly;
}
this.page.property('cookies', cookies).then(resolve).catch(reject);
});
}).on('error', reject);
}),
new Promise((resolve, reject) => {
req.pipe(fs.createWriteStream(save_path))
.on('close', resolve)
.on('error', reject);
})
]);*/
logger.profile(`download(download_url='${download_url}')`);
}
async download_image(download_url, stream) {
logger.profile(`download_image(download_url='${download_url}')`);
await Promise.all([
new Promise((resolve, reject) => {
this.client.once('donwload image', data => {
if (data.err)
reject(err);
else
stream.write(Buffer.from(data.data, 'base64'), resolve);
});
}),
this.page.evaluate(function (url) {
var img = new Image(), callback = function (err, data) {
callPhantom({
event: 'donwload image',
data: {
err: err && err.message,
data: data
}
});
};
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext("2d").drawImage(img, 0, 0);
callback(null, canvas.toDataURL("image/png").replace(/^data:image\/(png|jpg);base64,/, ""));
};
img.onerror = function () {
callback(new Error('Failed to fetch image.'));
};
img.src = url;
}, download_url)
]);
logger.profile(`download_image(download_url='${download_url}')`);
}