How to Set Size of Rendered Image - html2canvas

I'm confused with how to designate the size of the image that html2canvas generates. For example, I'd like to be able to have my DIV remain 400px x 400px but have the rendered image be 1200px x 1200px. I've looked at the documentation but I'm misunderstanding how to apply it. I've tried adding a.width: 1200; a.height: 1200; without luck.
What am I doing wrong?
My save function, from my JS:
$('#save').click(function() {
html2canvas($('#imagesave'), {
onrendered: function(canvas) {
var a = document.createElement('a');
a.href = canvas.toDataURL("image/png");
a.download = 'myfile.png';
a.click();
}
});
});
HTML
<div id="imagesave">
...
</div>
<button id="save">Save</button>
CSS
#imagesave {
background-color: white;
height: 400px;
width: 400px;
}

html2canvas($('#imagesave')[0], {
width: 1200,
height: 1200
}).then(function(canvas) {
var a = document.createElement('a');
a.href = canvas.toDataURL("image/png");
a.download = 'myfile.png';
a.click();
});
You need to pass width and height as options to html2canvas as mentioned in docs. Here is the fiddle for the same.
html2canvas($('#imagesave')[0], {
scale:3
}).then(function(canvas) {
var a = document.createElement('a');
a.href = canvas.toDataURL("image/png");
a.download = 'myfile.png';
a.click();
});
you can scale using scale attribute, which will scale horizontally and vertically with that much times.

Related

Getting county from click on OSM

Is it possible to detect state and county based on coordinates from a click on OSM map (US only)?
I can get the coordinated using click event in Leaflet JS:
map.on('click', function(ev) {
console.log(ev.latlng);
});
I can also get location data by doing something l;like this:
map.on("click", function(ev) {
var ln = ev.latlng["lng"],
lt = ev.latlng["lat"];
pt = "https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat="+lt+"&lon="+ln;
});
Which will return json data that looks like this:
https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=28.964162684075685&lon=-98.29776763916017
But I can't seem to be able to figure out what to do next... How do I get the county and state values from it?
You can just fetch, Ajax from jquery or use axios.
let config = {
minZoom: 2,
maxZoom: 18,
};
const zoom = 5;
const lat = 28.964162684075685;
const lng = -98.29776763916017;
const map = L.map("map", config).setView([lat, lng], zoom);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: '© OpenStreetMap contributors',
}).addTo(map);
map.on("click", function(e) {
const { lat, lng } = e.latlng;
const api = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&zoom=18&addressdetails=1`;
fetchData(api).then((data) => {
const { county, state } = data.address;
console.log(county, state);
});
});
async function fetchData(url) {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (err) {
console.error(err);
}
}
*,
:after,
:before {
box-sizing: border-box;
padding: 0;
margin: 0;
}
html {
height: 100%;
}
body,
html,
#map {
width: 100%;
height: 100%;
}
body {
position: relative;
min-height: 100%;
margin: 0;
padding: 0;
background-color: #f1f1f1;
}
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" rel="stylesheet" />
<div id="map"></div>

html2canvas screenshot size controle

I use this code from taking a screenshot & save it to pdf, I want to control the screenshot size like 400x700px.
<script type="text/javascript">
function genPDF() {
html2canvas(document.getElementById("all_content"), {
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img, 'JPEG',20,20);
doc.save("Businesscard-<?php echo $sss_name; ?>.pdf");
}
});
}
</script>
Add height and width attribute to get you desired outcome :
function genPDF() {
html2canvas(document.getElementById("all_content"), {
onrendered: function (canvas) {
canvas.setAttribute('width',400); /*this->add*/
canvas.setAttribute('height',700); /*this->add*/
var img = canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img, 'JPEG');
doc.save("Businesscard-<?php echo $sss_name; ?>.pdf");
}
});
}

When applying lockSwipes, I cannot scroll image in X-axis

I am developing an app using ionic v1.
I placed ion-slide-page in ion-slides and ion-scroll in ion-slide-page as shown below. This ion-scroll contains an image.
What I want to do is to keep the slide from moving left and right when the image is enlarged. (Like Facebook)
If I enlarge the image, I cannot scroll the image in X-axis.
Template:
<ion-slides options="options" slider="data.slider">
<ion-slide-page ng-repeat="image in post.imgs">
<ion-scroll
direction="xy"
scrollbar-x="false" scrollbar-y="false"
zooming="true" min-zoom="1" max_zoom="3"
overflow-scroll="false" locking="false" has-bouncing="true"
style="width: 100%; height: 100%" class="vertical-center"
delegate-handle="scrollHandle{{$index}}"
on-release="updateSlideStatus()">
<image style="width: 100%; height: 100%" ng-src="{{image}}"></image>
</ion-scroll>
</ion-slide-page>
</ion-slides>
Contorller:
$scope.$on("$ionicSlides.sliderInitialized", function(event, data){
console.log('ionic slides initialized');
$scope.slider = data.slider;
$scope.activeIndex = 0;
$scope.isSwipeLocked = false;
});
$scope.$on("$ionicSlides.slideChangeStart", function(event, data){
console.log('Slide change is beginning');
});
$scope.$on("$ionicSlides.slideChangeEnd", function(event, data) {
console.log('ionic slides change end');
$scope.activeIndex = data.slider.activeIndex;
$scope.previousIndex = data.slider.previousIndex;
});
$scope.updateSlideStatus = function() {
var zoom = $ionicScrollDelegate.$getByHandle('scrollHandle' + $scope.activeIndex).getScrollPosition().zoom;
if (zoom === 1) {
if ($scope.isSwipeLocked == true) {
$scope.slider.unlockSwipes();
$scope.isSwipeLocked = false;
}
} else {
if ($scope.isSwipeLocked == false) {
$scope.slider.lockSwipes();
$scope.isSwipeLocked = true;
}
}
};
Is there any idea?

How to capture a streaming video using WebRTC

the following code is similar to the one written in Mozilla Developer's Network: https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Taking_still_photos.
For some reasons,the webcam is not turned on when ran under a server.ejs. Only a button a shown. I suspect some editorial exists on the code, it would be nice if we could find where the problem stands? Thank you
<!doctype html>
<html lang="en">
<head>
<title> Introduction to WebRTC </title>
<link rel = "stylesheet" type="text/css" href="styles.css">
</head>
<body>
<p> <button id = "takeProfilePicture" type="button" autofocus="true">Create Profile Picture</button></p>
<video autoplay></video>
<video id="videoTag" autoplay></video>
<canvas id = "profilePicCanvas" style="display: none;"></canvas>
<div>
<img id = "profilePictureOutput">
</div>
<script>
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
var constraints = {
audio: false,
video: {
mandatory: {
minWidth : 240,
maxWidth : 240,
minHeight : 240,
maxHeight : 240
}
}
};
var videoArea = document.querySelector("video");
var profilePicCanvas = document.querySelector("#profilePicCanvas");
var profilePictureOutput = document.querySelector("#profilePictureOutput");
var takePicButton = document.querySelector("#takeProfilePicture");
var videoTag = document.querySelector("#videoTag");
var width = 240 ;
var height = 0 ;
var streaming = false ;
takePicButton.addEventListener('click', function(ev){
takeProfilePic();
ev.PreventDefault();
}, false;)
videoTag.addEventListener('canplay', function(ev){
if (!streaming) {
height = videoTag.videoHeight / (videoTag.videoWidth/width);
if (isNaN(height)) {
height = width / (4/3) ;
}
videoTag.setAttribute('width',width);
videoTag.setAttribute('height',height);
profilePicCanvas.setAttribute('width',width);
profilePicCanvas.setAttribute('height',height);
streaming = true ;
}
},false);
function takeProfilePic() {
var context = profilePicCanvas.getContext('2d');
if (width && height) {
profilePicCanvas.width = width ;
profilePicCanvas.height = height ;
context.drawImage(videoTag, 0 , 0 , width, height);
var data = profilePicCanvas.toDataURL('image/png');
profilePictureOutput.setAttribute('src',data);
}
}
navigator.getUserMedia(constraints, onSuccess, onError);
function onSuccess(stream) {
console.log("Sucess! We have a stream!");
videoArea.src = window.URL.createObjectURL(stream);
videoArea.className = "grayscale_filter";
videoArea.play() ;
}
function onError(error) {
console.log("Error with getUserMedia: ", error);
}
</script>
</body>
</html>

nvd3 Display 2 Chart

at my work I try to print some graph with nvd3.
But I can only display 1 graph on my page, and I don't understand why the previous graph don't appear.
Could you give me some hint ?
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<link href="lib/css/nv.d3.css" rel="stylesheet">
</head>
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: auto;
position: relative;
width: 960px;
}
/**********
* Legend
*/
.nvd3 .nv-legend .nv-series {
cursor: pointer;
}
.nvd3 .nv-legend .nv-disabled circle {
fill-opacity: 0;
}
text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
form {
position: absolute;
right: 10px;
top: 10px;
}
#chart, #pid svg {
height: 600px;
width: 600px;
}
</style>
<div id="pid">
<svg></svg>
</div>
<div id="chart">
<svg></svg>
</div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="lib/js/nv.d3.js"></script>
<script>
var divs = ["pid", "chart"];
divs["pid"]= {id:"#pid svg", datam:[
{
values:[
{x:"M",y:1},
{x:"T",y:2},
{x:"W",y:3},
{x:"R",y:3},
{x:"F",y:4},
{x:"S",y:5},
{x:"U",y:6}
],
key:"Apples"
},
{
values:[
{x:"M",y:5},
{x:"T",y:2},
{x:"W",y:6},
{x:"R",y:8},
{x:"F",y:2},
{x:"S",y:4},
{x:"U",y:1}
],
key:"Zebras"
},
{
values:[
{x:"M",y:4},
{x:"T",y:6},
{x:"W",y:5},
{x:"R",y:7},
{x:"F",y:7},
{x:"S",y:2},
{x:"U",y:5}
],
key:"Bananas"
}
], color:['purple', 'black', 'yellow']};
divs["chart"]= {id:"#chart svg", datam:[
{
values:[
{x:"M",y:1},
{x:"T",y:2},
{x:"W",y:3},
{x:"R",y:3},
{x:"F",y:4},
{x:"S",y:5},
{x:"U",y:6}
],
key:"Apples"
},
{
values:[
{x:"M",y:5},
{x:"T",y:2},
{x:"W",y:6},
{x:"R",y:8},
{x:"F",y:2},
{x:"S",y:4},
{x:"U",y:1}
],
key:"Zebras"
}
], color:['red', 'blue', 'green']};
console.log(divs)
var i=0;
var chart = new Array(2);
nv.render = function render(step) {
// number of graphs to generate in each timeout loop
step = step || 1;
nv.render.active = true;
nv.dispatch.render_start();
setTimeout(function() {
var chart, graph;
for (var i = 0; i < step && (graph = nv.render.queue[i]); i++) {
chart = graph.generate();
if (typeof graph.callback == typeof(Function)) graph.callback(chart);
nv.graphs.push(chart);
}
nv.render.queue.splice(0, i);
if (nv.render.queue.length) setTimeout(arguments.callee, 0);
else {
nv.dispatch.render_end();
nv.render.active = false;
}
}, 0);
};
nv.render.active = false;
nv.render.queue = [];
for (var key in divs) {
console.log(i);
nv.addGraph(function(obj) {
if (typeof arguments[0] === typeof(Function)) {
obj = {generate: arguments[0], callback: arguments[1]};
}
nv.render.queue.push(obj);
console.log(nv.render.queue.length);
if (!nv.render.active) {
nv.render();
}
chart[i] = nv.models.multiBarChart().showControls(true).groupSpacing(0.5).color(divs[key]['color']);
chart[i].yAxis
.tickFormat(d3.format(',.1f'));
d3.select(divs[key]['id'])
.datum(divs[key]['datam'])
.transition().duration(500).call(chart[i]);
nv.utils.windowResize(chart[i].update);
return chart[i];
});
i++;
};
// render function is used to queue up chart rendering
// in non-blocking timeout functions
</script>
I hope you colud help me, thanks.