Why does mic.getLevel() not go to 0 again after getAudioContext().suspend() is called? - dom

Making a voice recorder visualizer and I'm just about finished but there's one thing, After I stop the recording, the values in mic.getLevel() do not go back to 0 but instead it seems like the last value that was recorded in mic.getLeve() is stored permanently and added to the height of my ellipse so the ellipse would then have a height of some value rather than 0 which it started with, is there anyway to fix this?
var recordAudio;
function setup() {
createCanvas(windowWidth, windowHeight);
recordAudio = new AudioFile()
}
function draw() {
background(0);
recordAudio.draw();
recordAudio.setup();
recordAudio.drawBorder();
recordAudio.drawNode();
}
function AudioFile() {
this.nodes = [];
var speed = 2;
var endBorder;
var mic = new p5.AudioIn();
var micLevel;
var level;
var recorder = new p5.SoundRecorder();
var soundFile = new p5.SoundFile();
var button = createButton('Start Recording');
var state = 0;
this.draw = function() {
background(0);
level = mic.getLevel();
micLevel = floor(map(level, 0, 0.6545, 0, 50));
}
this.drawNode = function() {
if (frameCount % 5 == 0) {
this.addNode()
}
for (var i = 0; i < this.nodes.length; i++) {
var node = this.nodes[i]
for (var j = 0; j < node.length; j++) {
fill(255);
node[j].x -= speed;
ellipse(node[j].x, node[j].y, node[j].width, node[j].height)
}
if (node[0].x < endBorder) {
this.nodes.splice(i, 1);
}
}
}
this.drawBorder = function() {
var x = windowWidth / 9;
var y = windowHeight / 10;
var width = (windowWidth / 9) * 7;
var height = windowHeight - y * 2;
stroke(255);
strokeWeight(2);
noFill();
rect(x, y, width, height);
}
this.addNode = function() {
this.nodes.push(
[{
x: ((windowWidth / 9) * 8) - 10,
y: windowHeight / 2,
width: 5,
height: 5 * micLevel
}])
}
this.setup = function() {
endBorder = windowWidth / 9 + 5;
mic.start();
recorder.setInput(mic);
button.position(windowWidth / 9, windowHeight / 10);
button.style('font-size', '18px');
button.mousePressed(this.recording)
}
this.recording = function() {
if (state === 0 && mic.enabled) {
button.html("Stop Recording");
getAudioContext().resume()
recorder.record(soundFile);
state++
} else if (state === 1) {
button.html("Start Recording");
getAudioContext().suspend();
recorder.stop();
state++;
} else if (state === 2) {
save(soundFile, 'Sound.wav');
state = 0;
}
}
}
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet">
<script src="p5.min.js"></script>
<script src="p5.dom.js"></script>
<script src="p5.sound.js"></script>
<script src="sketch.js"></script>
<!--<link rel="stylesheet" type="text/css" href="style.css">-->
<style>
body {
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div id="Button">
</div>
</body>
</html>

I ended up making a global variable called listening and used that in an if statement in draw to set the level to either mic.getLevel() or 0 based on if listening is true or false.

Related

Get two offset points between two points

Hi I need help finding coordinate or points offset from two endpoints of a line. In my program, I would like to specify the two points and the offset. Then I need to calculate the two offset coordinates.
I worked something out using trigonometry but it only works in some cases and when the line is in the positive quadrant.
Here is an image describing what I need to find:
Points on line
Ok so I need to find X3,Y3 and X4,Y4 coordinates.
My method I followed:
Calculate angle:
Ang = atan((Y2 - Y1)/(X2 - X1))
To find X3:
X3 = X1 + Offset * Cos(Ang)
The same concept for Y3
The issue is that if the line is in a different quadrant the point info is not correct... Any help, please.
This question is a clear case for using 2d vector math. The idea is that we subtract p1 from p2 to give us a vector that describes the length and direction of the line. We then normalize this vector, such that it has a length of 1. If you then multiply this normalized vector with the number of units you'd like to move away from the end and add the result to the end-point, you'll have a new point.
Consider an example walking along the x axis:
p1 = 0,0
p2 = 10,0
dif = p2 - p1 = (10,0)
length is 10, so it's 10 times too long - we divide it by 10 to get a vector 1 unit long.
If we then move 5 times (1,0), we end up at 5,0 - 5 units away, bewdy!
Here's a function that achieves the same thing:
function calcOffsetPoint(x1,y1, x2,y2, distTowardsP2fromP1)
{
var p1 = new vec2d(x1,y1);
var p2 = new vec2d(x2,y2);
var delta = p2.sub(p1);
var dirVec = delta.clone();
dirVec.normalize();
dirVec.timesEquals(distTowardsP2fromP1);
var resultPoint = p1.add(dirVec);
return resultPoint;
}
As you can see, this makes use of something I've called vec2d. There's a copy of it in the following snippet:
"use strict";
function byId(id){return document.getElemetById(id)}
function newEl(tag){return document.createElement(tag)}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
var end1 = new vec2d(0,0);
var end2 = new vec2d(10,0);
var midPoint = calcOffsetPoint(end1.x,end1.y, end2.x,end2.y, 5);
console.log( midPoint.toStringN(2) );
}
class vec2d
{
constructor(x=0, y=0)
{
this.mX = x;
this.mY = y;
}
get x(){return this.mX;}
set x(newX){this.mX = newX;}
get y(){return this.mY;}
set y(newY){this.mY = newY;}
add(other)
{
return new vec2d(this.x+other.x, this.y+other.y);
}
sub(other)
{
return new vec2d(this.x-other.x, this.y-other.y);
}
timesEquals(scalar)
{
this.x *= scalar;
this.y *= scalar;
return this;
}
divByEquals(scalar)
{
this.x /= scalar;
this.y /= scalar;
return this;
}
dotProd(other)
{
return this.x*other.x + this.y*other.y;
}
length()
{
return Math.hypot(this.x, this.y);
}
normalize()
{
this.divByEquals( this.length() );
return this;
}
perpendicular()
{
var tmp = this.x;
this.x = -this.y;
this.y = tmp;
return this;
}
clone()
{
return vec2d.clone(this);
}
static clone(other)
{
return new vec2d(other.x, other.y);
}
toString(){return `vec2d {x: ${this.x}, y: ${this.y}}`}
toStringN(n){return `vec2d {x: ${this.x.toFixed(n)}, y: ${this.y.toFixed(n)}}`}
}
function calcOffsetPoint(x1,y1, x2,y2, distTowardsP2fromP1)
{
var p1 = new vec2d(x1,y1);
var p2 = new vec2d(x2,y2);
var delta = p2.sub(p1);
var dirVec = delta.clone();
dirVec.normalize();
dirVec.timesEquals(distTowardsP2fromP1);
var resultPoint = p1.add(dirVec);
return resultPoint;
}
I had some spare time over the weekend, so put together a working demo of the image you posted. Have a play around. Make sure you run it in full-screen, so you can see the sliders that set the offsets for p3 and p4. Disregard the coordinate-system transformation stuff, that's just there to allow me to make an image the same dimensions as your image yet conveniently display it in a window with about 5% the area. The questions come from the exercise section of some old text-book I was reading over the weekend.
"use strict";
class vec2d
{
constructor(x=0,y=0)
{
this.x = x;
this.y = y;
}
abs()
{
this.x = Math.abs(this.x);
this.y = Math.abs(this.y);
return this;
}
add(vec1)
{
return new vec2d(this.x+vec1.x, this.y+vec1.y);
}
sub(vec1)
{
return new vec2d(this.x-vec1.x, this.y-vec1.y);
}
mul(scalar)
{
return new vec2d(this.x*scalar, this.y*scalar);
}
plusEquals(vec1)
{
this.x += vec1.x;
this.y += vec1.y;
return this;
}
minusEquals(vec1)
{
this.x -= vec1.x;
this.y -= vec1.y;
return this;
}
timesEquals(scalar)
{
this.x *= scalar;
this.y *= scalar;
return this;
}
divByEquals(scalar)
{
this.x /= scalar;
this.y /= scalar;
return this;
}
normalize()
{
var len = this.length;
this.x /= len;
this.y /= len;
return this;
}
get length()
{
//return Math.sqrt( (this.x*this.x)+(this.y*this.y) );
return Math.hypot( this.x, this.y );
}
set length(newLen)
{
var invLen = newLen / this.length;
this.timesEquals(invLen);
}
dotProd(vec1)
{
return this.x*vec1.x + this.y*vec1.y;
}
perp()
{
var tmp = this.x;
this.x = -this.y;
this.y = tmp;
return this;
}
wedge(other)
{ // computes an area for parallelograms
return this.x*other.y - this.y*other.x;
}
static clone(other)
{
var result = new vec2d(other.x, other.y);
return result;
}
clone() // clone self
{
return vec2d.clone(this);
}
setTo(other)
{
this.x = other.x;
this.y = other.y;
}
get(){ return {x:this.x, y:this.y}; }
toString(){ return `vec2d {x: ${this.x}, y: ${this.y}}` }
toStringN(n){ return `vec2d {x: ${this.x.toFixed(n)}, y: ${this.y.toFixed(n)}}` }
print(){console.log(this.toString())}
};
class mat3
{
static clone(other)
{
var result = new mat3();
other.elems.forEach(
function(el, index, collection)
{
result.elems[index] = el;
}
);
return result;
}
clone()
{
return mat3.clone(this);
}
constructor(a,b,c,d,e,f)
{
if (arguments.length < 6)
this.setIdentity();
else
this.elems = [a,b,0,c,d,0,e,f,1];
}
setIdentity()
{
this.elems = [1,0,0, 0,1,0, 0,0,1];
}
multiply(other, shouldPrepend)
{
var a, b, c = new mat3();
if (shouldPrepend === true)
{
a = other;
b = this;
}
else
{
a = this;
b = other;
}
c.elems[0] = a.elems[0]*b.elems[0] + a.elems[1]*b.elems[3] + a.elems[2]*b.elems[6];
c.elems[1] = a.elems[0]*b.elems[1] + a.elems[1]*b.elems[4] + a.elems[2]*b.elems[7];
c.elems[2] = a.elems[0]*b.elems[2] + a.elems[1]*b.elems[5] + a.elems[2]*b.elems[8];
// row 1
c.elems[3] = a.elems[3]*b.elems[0] + a.elems[4]*b.elems[3] + a.elems[5]*b.elems[6];
c.elems[4] = a.elems[3]*b.elems[1] + a.elems[4]*b.elems[4] + a.elems[5]*b.elems[7];
c.elems[5] = a.elems[3]*b.elems[2] + a.elems[4]*b.elems[5] + a.elems[5]*b.elems[8];
// row 2
c.elems[6] = a.elems[6]*b.elems[0] + a.elems[7]*b.elems[3] + a.elems[8]*b.elems[6];
c.elems[7] = a.elems[6]*b.elems[1] + a.elems[7]*b.elems[4] + a.elems[8]*b.elems[7];
c.elems[8] = a.elems[6]*b.elems[2] + a.elems[7]*b.elems[5] + a.elems[8]*b.elems[8];
for (var i=0; i<9; i++)
this.elems[i] = c.elems[i];
}
transformVec2s(pointList)
{
var i, n = pointList.length;
for (i=0; i<n; i++)
{
var x = pointList[i].x*this.elems[0] + pointList[i].y*this.elems[3] + this.elems[6];
var y = pointList[i].x*this.elems[1] + pointList[i].y*this.elems[4] + this.elems[7];
pointList[i].x = x;
pointList[i].y = y;
}
}
makeTransformedPoints(pointList)
{
var result = [];
for (var i=0,n=pointList.length;i<n;i++)
{
var x = pointList[i].x*this.elems[0] + pointList[i].y*this.elems[3] + this.elems[6];
var y = pointList[i].x*this.elems[1] + pointList[i].y*this.elems[4] + this.elems[7];
result.push( new vec2d(x,y) );
}
return result;
}
rotate(degrees, shouldPrepend)
{
var tmp = new mat3();
tmp.elems[0] = Math.cos( degrees/180.0 * Math.PI );
tmp.elems[1] = -Math.sin( degrees/180.0 * Math.PI );
tmp.elems[3] = -tmp.elems[1];
tmp.elems[4] = tmp.elems[0];
this.multiply(tmp, shouldPrepend);
}
scaleEach(scaleX, scaleY, shouldPrepend)
{
var tmp = new mat3();
tmp.elems[0] = scaleX;
tmp.elems[4] = scaleY;
this.multiply(tmp, shouldPrepend);
}
scaleBoth(scaleAmount, shouldPrepend)
{
var tmp = new mat3();
tmp.elems[0] = scaleAmount;
tmp.elems[4] = scaleAmount;
this.multiply(tmp, shouldPrepend);
}
translate(transX, transY, shouldPrepend)
{
var tmp = new mat3();
tmp.elems[6] = transX;
tmp.elems[7] = transY;
this.multiply(tmp, shouldPrepend);
}
determinant()
{
var result, a, b;
a = ( (this.elems[0]*this.elems[4]*this.elems[8])
+ (this.elems[1]*this.elems[5]*this.elems[6])
+ (this.elems[2]*this.elems[3]*this.elems[7]) );
b = ( (this.elems[2]*this.elems[4]+this.elems[6])
+ (this.elems[1]*this.elems[3]+this.elems[8])
+ (this.elems[0]*this.elems[5]+this.elems[7]) );
result = a - b;
return result;
}
isInvertible()
{
return (this.determinant() != 0);
}
invert()
{
var det = this.determinant();
if (det == 0)
return;
var a,b,c,d,e,f,g,h,i;
a = this.elems[0]; b = this.elems[1]; c = this.elems[2];
d = this.elems[3]; e = this.elems[4]; f = this.elems[5];
g = this.elems[6]; h = this.elems[7]; i = this.elems[8];
this.elems[0] = (e*i - f*h); this.elems[1] = -((b*i) - (c*h)); this.elems[2] = (b*f)-(c*e);
this.elems[3] = -(d*i - f*g); this.elems[4] = (a*i) - (c*g); this.elems[5] = -( (a*f) - (c*d) );
this.elems[6] = (d*h - e*g); this.elems[7] = -((a*h) - (b*g)); this.elems[8] = (a*e)-(b*d);
var detInv = 1.0 / det;
for (var i=0; i<9; i++)
this.elems[i] *= detInv;
return this;
}
reset()
{
this.setIdentity();
}
print()
{
var str = '';
for (var i=0; i<9; i++)
{
if (i && i%3==0)
str += "\n";
str += " " + this.elems[i].toFixed(5);
}
console.log(str);
}
}
function byId(id){return document.getElementById(id)}
function newEl(tag){return document.createElement(tag)}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
byId('output').addEventListener('mousemove', onMouseMove, false);
byId('slider1').addEventListener('input', onSliderInput, false);
byId('slider2').addEventListener('input', onSliderInput, false);
draw();
}
//(400-48)/400 = 0.88
var invMat, svgInvMat;
function onMouseMove(evt)
{
var mousePos = new vec2d(evt.offsetX,evt.offsetY);
var worldPos = mousePos.clone();
invMat.transformVec2s( [worldPos] );
byId('screenMouse').textContent = `screen: ${mousePos.x},${mousePos.y}`;
byId('worldMouse').textContent = `world: ${worldPos.x.toFixed(1)}, ${worldPos.y.toFixed(1)}`;
}
function onSliderInput(evt)
{
draw();
}
function updateSliderLabels()
{
byId('ofset1Output').textContent = byId('slider1').value;
byId('ofset2Output').textContent = byId('slider2').value;
}
function draw()
{
var can = byId('output');
var ctx = can.getContext('2d');
ctx.clearRect(0,0,can.width,can.height);
var orientMat = evaluateViewOrientationMatrix(0.06*can.width,can.height-24, 0,-1);
var scaleMat = computeWindowToViewPortMatrix(2052,1317, can.width,can.height);
var viewMat = scaleMat.clone();
viewMat.multiply(orientMat);
console.log('viewMat');
viewMat.print();
invMat = viewMat.clone().invert();
for (var i=0; i<9; i++)
invMat.elems[i] /= invMat.elems[8];
ctx.strokeStyle = '#fff';
var axisPts = [ new vec2d(0,1070), new vec2d(0,0), new vec2d(0.88*2052,0) ]; // xAxis line 88% of image width
var axis = viewMat.makeTransformedPoints(axisPts);
drawLine(axis[0].x,axis[0].y, axis[1].x,axis[1].y, ctx);
drawLine(axis[1].x,axis[1].y, axis[2].x,axis[2].y, ctx);
var lineEnds = [new vec2d(330,263), new vec2d(1455,809)];
var pts2 = viewMat.makeTransformedPoints(lineEnds);
drawCircle(pts2[0].x,pts2[0].y, 4, ctx);
drawCircle(pts2[1].x,pts2[1].y, 4, ctx);
drawLine(pts2[0].x,pts2[0].y, pts2[1].x,pts2[1].y, ctx);
var rawP3 = calcOffsetCoords(lineEnds[0].x,lineEnds[0].y, lineEnds[1].x,lineEnds[1].y, byId('slider1').value);
var rawP4 = calcOffsetCoords(lineEnds[1].x,lineEnds[1].y, lineEnds[0].x,lineEnds[0].y, byId('slider2').value);
var ofsPts = viewMat.makeTransformedPoints( [rawP3, rawP4] );
drawCircle(ofsPts[0].x,ofsPts[0].y, 4, ctx);
drawCircle(ofsPts[1].x,ofsPts[1].y, 4, ctx);
updateSliderLabels();
}
function calcOffsetCoords(x1,y1, x2,y2, offset)
{
var dx = x2 - x1;
var dy = y2 - y1;
var lineLen = Math.hypot(dx, dy);
var normDx=0, normDy=0;
if (lineLen != 0)
{
normDx = dx / lineLen;
normDy = dy / lineLen;
}
var resultX = x1 + (offset * normDx);
var resultY = y1 + (offset * normDy);
return {x:resultX,y:resultY};//new vec2d(resultX,resultY); //{x:resultX,y:resultY};
}
// Exercise 6-1:
// Write a procedure to implement the evaluateViewOrientationMatrix function that calculates the elements of the
// matrix for transforming world coordinates to viewing coordinates, given the viewing coordinate origin Porigin and
// the viewUp vector
function evalViewOrientMatrix(screenOriginX,screenOriginY, worldUpVectorX,worldUpVectorY)
{
var worldUp = {x: worldUpVectorX, y: worldUpVectorY};
var len = Math.hypot(worldUp.x, worldUp.y);
if (len != 0)
len = 1.0 / len;
worldUp.x *= len;
worldUp.y *= len;
var worldRight = {x: worldUp.y, y: -worldUp.x};
var rotMat = svg.createSVGMatrix();
rotMat.a = worldRight.x;
rotMat.b = worldRight.y;
rotMat.c = worldUp.x;
rotMat.d = worldUp.y;
var transMat = svg.createSVGMatrix();
transMat = transMat.translate(screenOriginX, screenOriginY);
var result = rotMat.multiply(transMat);
return result;
}
function evaluateViewOrientationMatrix(screenOriginX,screenOriginY, worldUpVectorX,worldUpVectorY)
{
var worldUp = new vec2d(worldUpVectorX, worldUpVectorY);
worldUp.normalize();
var worldRight = worldUp.clone().perp();
var rotMat = new mat3();
rotMat.elems[0] = worldRight.x; rotMat.elems[1] = worldRight.y;
rotMat.elems[3] = worldUp.x; rotMat.elems[4] = worldUp.y;
var transMat = new mat3();
transMat.translate(screenOriginX,screenOriginY);
var result = rotMat.clone();
result.multiply(transMat);
return result;
}
/*
0 1 2
3 4 5
6 7 8
translation
-----------
1 0 0
0 1 0
tX tY 1
scaling
---------
sX 0 0
0 sY 0
0 0 1
rotation
--------
cosX -sinX 0
sinX cosX 0
0 0 1
*/
// Exercise 6-2:
// Derive the window to viewport transformation equations 6-3 by first scaling the window to
// the size of the viewport and then translating the scaled window to the viewport position
function computeWindowToViewPortMatrix(windowWidth,windowHeight,viewPortWidth,viewPortHeight)
{
var result = new mat3();
result.scaleEach(viewPortWidth/windowWidth,viewPortHeight/windowHeight);
return result;
}
// returns an SVGMatrix
function compWnd2ViewMat(windowWidth,windowHeight,viewPortWidth,viewPortHeight)
{
var result = svg.createSVGMatrix();
return result.scaleNonUniform(viewPortWidth/windowWidth,viewPortHeight/windowHeight);
}
function drawLine(x1,y1,x2,y2,ctx)
{
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
function drawCircle(x,y,radius,ctx)
{
ctx.beginPath();
ctx.arc(x, y, radius, 0, (Math.PI/180)*360, false);
ctx.stroke();
ctx.closePath();
}
canvas
{
background-color: black;
}
.container
{
display: inline-block;
background-color: #888;
border: solid 4px #555;
}
#screenMouse, #worldMouse, .control
{
display: inline-block;
width: calc(513px/2 - 2*8px);
margin-left: 8px;
}
<body>
<div class='container'>
<canvas id='output' width='513' height='329'></canvas><br>
<div id='screenMouse'></div><div id='worldMouse'></div>
<div>
<div class='control'>P2 ofs: <input id='slider1' type='range' min='0' max='500' value='301'><span id='ofset1Output'></span></div>
<div class='control'>P3 ofs: <input id='slider2' type='range' min='0' max='500' value='285'><span id='ofset2Output'></span></div>
</div>
</div>
</body>

Bing Maps containsLocation function

I have a site that uses both Bing and Google maps. Each function has a Bing and Google version. I am having trouble duplicating the google.maps.geometry.poly.containsLocation function in Bing maps. Is there such a thing?
Basically I build a polygon and am looking to determine if a pushpin is located inside the polygon on the map.
Bing Maps V8 has a Spatial Math module which can do this calculation for you easily using the intersects function:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
</head>
<body>
<div id='myMap' style='width: 100vw; height: 100vh;'></div>
<script type='text/javascript'>
function load() {
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'YOUR BING MAPS KEY'
});
//Create a polygon and location for testing.
var center = map.getCenter();
var polygon = new Microsoft.Maps.Polygon([new Microsoft.Maps.Location(center.latitude - 0.05, center.longitude - 0.05),
new Microsoft.Maps.Location(center.latitude + 0.01, center.longitude - 0.05),
new Microsoft.Maps.Location(center.latitude + 0.01, center.longitude + 0.05)], { fillColor: 'yellow', strokeColor: 'orange',
strokeThickness: 5, strokeDashArray: [1, 2, 5, 10] });
map.entities.push(polygon);
var location = new Microsoft.Maps.Location(center.latitude, center.longitude);
//Load the Spatial Math module
Microsoft.Maps.loadModule('Microsoft.Maps.SpatialMath', function () {
//Check to see if the shapes intersect.
var intersects = Microsoft.Maps.SpatialMath.Geometry.intersects(location, polygon);
if(intersects){
alert("The location is inside in the polygon");
} else {
alert("The location is NOT inside in the polygon");
}
});
}
</script>
<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=load' async defer></script>
</body>
</html>
You can add your own method to do so using the extensibility of Bing Maps AJAX control. You can put that extension method on the Microsoft.Maps.Location class.
Microsoft.Maps.Location.prototype.IsInPolygon=function(polygon)
{
var isInside = false;
var j = 0;
var x = this.longitude;
var y = this.latitude;
var paths = polygon.getLocations();
for (var i = 0; i < paths.length ; i++) {
j++;
if (j == paths.length) { j = 0; }
if (((paths[i].latitude < y) && (paths[j].latitude >= y)) || ((paths[j].latitude < y) && (paths[i].latitude >= y))) {
if (paths[i].longitude + (y - paths[i].latitude) / (paths[j].latitude - paths[i].latitude) * (paths[j].longitude - paths[i].longitude) < x) {
isInside = !isInside
}
}
}
return isInside;
};
Here is a working example with Bing Maps V8:
<!DOCTYPE html>
<html>
<head>
<title>Bing Maps - V8 - Polygon test</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
</head>
<body>
<div id='myMap' style='width: 100vw; height: 100vh;'></div>
<script type='text/javascript'>
function load() {
Microsoft.Maps.Location.prototype.IsInPolygon=function(polygon)
{
var isInside = false;
var j = 0;
var x = this.longitude;
var y = this.latitude;
var paths = polygon.getLocations();
for (var i = 0; i < paths.length ; i++) {
j++;
if (j == paths.length) { j = 0; }
if (((paths[i].latitude < y) && (paths[j].latitude >= y)) || ((paths[j].latitude < y) && (paths[i].latitude >= y))) {
if (paths[i].longitude + (y - paths[i].latitude) / (paths[j].latitude - paths[i].latitude) * (paths[j].longitude - paths[i].longitude) < x) {
isInside = !isInside
}
}
}
return isInside;
};
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'YOUR KEY'
});
var center = map.getCenter();
var polygon = new Microsoft.Maps.Polygon([new Microsoft.Maps.Location(center.latitude - 0.05, center.longitude - 0.05),
new Microsoft.Maps.Location(center.latitude + 0.01, center.longitude - 0.05),
new Microsoft.Maps.Location(center.latitude + 0.01, center.longitude + 0.05)], { fillColor: 'yellow', strokeColor: 'orange',
strokeThickness: 5, strokeDashArray: [1, 2, 5, 10] });
map.entities.push(polygon);
var location = new Microsoft.Maps.Location(center.latitude, center.longitude);
alert("The location is inside in the polygon : " + location.IsInPolygon(polygon));
}
</script>
<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=load' async defer></script>
</body>
</html>

jsPDF multi page PDF with HTML renderer

I am using jsPDF in my site to generate PDFs. But now I have multiple DIVs to print in a single PDF. which may take 2 to 3 pages.
For example:
<div id="part1">
content
</div>
<div id="part2">
content
</div>
<div id="part2">
content
</div>
my JS code
This works but not as I expected, It add a part of the content(which cannot be included in more than one page).
It removes html tags like br, h1 etc.
function formtoPDF() {
jsPDF.API.mymethod = function() {
// 'this' will be ref to internal API object. see jsPDF source
// , so you can refer to built-in methods like so:
// this.line(....)
// this.text(....)
};
var doc = new jsPDF();
doc.mymethod();
var pdfPart1 = jQuery('#genPDFpart1');
var pdfPart2 = jQuery(".ltinerary");
var pdfPart3 = jQuery("#domElementHTML");
var specialElementHandlers = {
'#loadVar': function(element, renderer) {
return true;
}
};
doc.fromHTML(pdfPart1.html() + pdfPart3.html() + pdfPart3.html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.output('save', 'Download.pdf');
}
What's the solution for this?
I have the same working issue. Searching in MrRio github I found this: https://github.com/MrRio/jsPDF/issues/101
Basically, you have to check the actual page size always before adding new content
doc = new jsPdf();
...
pageHeight= doc.internal.pageSize.height;
// Before adding new content
y = 500 // Height position of new content
if (y >= pageHeight)
{
doc.addPage();
y = 0 // Restart height position
}
doc.text(x, y, "value");
here's an example using html2canvas & jspdf, although how you generate the canvas doesn't matter--we're just going to use the height of that as the breakpoint on a for loop, in which a new page is created and content added to it.
after the for loop, the pdf is saved.
function makePDF() {
var quotes = document.getElementById('container-fluid');
html2canvas(quotes).then((canvas) => {
//! MAKE YOUR PDF
var pdf = new jsPDF('p', 'pt', 'letter');
for (var i = 0; i <= quotes.clientHeight/980; i++) {
//! This is all just html2canvas stuff
var srcImg = canvas;
var sX = 0;
var sY = 980*i; // start 980 pixels down for every new page
var sWidth = 900;
var sHeight = 980;
var dX = 0;
var dY = 0;
var dWidth = 900;
var dHeight = 980;
window.onePageCanvas = document.createElement("canvas");
onePageCanvas.setAttribute('width', 900);
onePageCanvas.setAttribute('height', 980);
var ctx = onePageCanvas.getContext('2d');
// details on this usage of this function:
// https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Slicing
ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight);
// document.body.appendChild(canvas);
var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0);
var width = onePageCanvas.width;
var height = onePageCanvas.clientHeight;
//! If we're on anything other than the first page,
// add another page
if (i > 0) {
pdf.addPage(612, 791); //8.5" x 11" in pts (in*72)
}
//! now we declare that we're working on that page
pdf.setPage(i+1);
//! now we add content to that page!
pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62));
}
//! after the for loop is finished running, we save the pdf.
pdf.save('Test.pdf');
});
}
I found the solution on this page: https://github.com/MrRio/jsPDF/issues/434
From the user: wangzhixuan
I copy the solution here:
// suppose your picture is already in a canvas
var imgData = canvas.toDataURL('image/png');
/*
Here are the numbers (paper width and height) that I found to work.
It still creates a little overlap part between the pages, but good enough for me.
if you can find an official number from jsPDF, use them.
*/
var imgWidth = 210;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF('p', 'mm');
var position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
doc.save( 'file.pdf');
var doc = new jsPDF('p', 'mm');
var imgData = canvas.toDataURL('image/png');
var pageHeight= doc.internal.pageSize.getHeight();
var pageWidth= doc.internal.pageSize.getWidth();
var imgheight = $('divName').height() * 25.4 / 96; //px to mm
var pagecount = Math.ceil(imgheight / pageHeight);
/* add initial page */
doc.addPage('l','mm','a4');
doc.addImage(imgData, 'PNG', 2, 0, pageWidth-4, 0);
/* add extra pages if the div size is larger than a a4 size */
if (pagecount > 0) {
var j = 1;
while (j != pagecount) {
doc.addPage('l','mm','a4');
doc.addImage(imgData, 'PNG', 2, -(j * pageHeight), pageWidth-4, 0);
j++;
}
}
You can use html2canvas plugin and jsPDF both. Process order:
html to png & png to pdf
Example code:
jQuery('#part1').html2canvas({
onrendered: function( canvas ) {
var img1 = canvas.toDataURL('image/png');
}
});
jQuery('#part2').html2canvas({
onrendered: function( canvas ) {
var img2 = canvas.toDataURL('image/png');
}
});
jQuery('#part3').html2canvas({
onrendered: function( canvas ) {
var img3 = canvas.toDataURL('image/png');
}
});
var doc = new jsPDF('p', 'mm');
doc.addImage( img1, 'PNG', 0, 0, 210, 297); // A4 sizes
doc.addImage( img2, 'PNG', 0, 90, 210, 297); // img1 and img2 on first page
doc.addPage();
doc.addImage( img3, 'PNG', 0, 0, 210, 297); // img3 on second page
doc.save("file.pdf");
$( document ).ready(function() {
$('#cmd').click(function() {
var options = {
pagesplit: true //include this in your code
};
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML($("#pdfContent"), 15, 15, options, function() {
pdf.save('Menu.pdf');
});
});
});
This is my first post which support only a single page http://www.techumber.com/html-to-pdf-conversion-using-javascript/
Now, the second one will support the multiple pages.
http://www.techumber.com/how-to-convert-html-to-pdf-using-javascript-multipage/
Below is my code but the problem is that the document doesn't split to display the other part of the document in a new page.
Please improve this code.
<script type='text/javascript'>
$(document).on("click", "#btnExportToPDF", function () {
var table1 =
tableToJson($('#table1')[0]),
cellWidth =42,
rowCount = 0,
cellContents,
leftMargin = 2,
topMargin = 12,
topMarginTable =5,
headerRowHeight = 13,
rowHeight = 12,
l = {
orientation: 'p',
unit: 'mm',
format: 'a3',
compress: true,
fontSize: 11,
lineHeight: 1,
autoSize: false,
printHeaders: true
};
var doc = new jsPDF(l,'pt', 'letter');
doc.setProperties({
title: 'Test PDF Document',
subject: 'This is the subject',
author: 'author',
keywords: 'generated, javascript, web 2.0, ajax',
creator: 'author'
});
doc.cellInitialize();
$.each(table1, function (i, row)
{
rowCount++;
$.each(row, function (j, cellContent) {
if (rowCount == 1) {
doc.margins = 1;
doc.setFont("Times New Roman");
doc.setFontType("bold");
doc.setFontSize(11);
doc.cell(leftMargin, topMargin, cellWidth, headerRowHeight, cellContent, i)
}
else if (rowCount == 2) {
doc.margins = 1;
doc.setFont("Times ");
doc.setFontType("normal");
// or for normal font type use ------ doc.setFontType("normal");
doc.setFontSize(11);
doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
}
else {
doc.margins = 1;
doc.setFont("Times ");
doc.setFontType("normal ");
doc.setFontSize(11);
doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
// 1st=left margin 2nd parameter=top margin, 3rd=row cell width 4th=Row height
}
})
})
doc.save('sample Report.pdf');
});
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
// go through cells
for (var i=1; i<table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
</script>
Automatically not split data to multi pages. You may split manually.
If your ( rowCount * rowHeight ) > 420mm ( A3 Height in mm ) add new page function. ( Sorry I can't edit your code without run )
After add new page leftMargin, topMargin = 0; ( start over )
I added sample code with yours. I hope it's right.
else {
doc.margins = 1;
doc.setFont("Times ");
doc.setFontType("normal ");
doc.setFontSize(11);
if ( rowCount * rowHeight > 420 ) {
doc.addPage();
rowCount = 3; // skip 1 and 2 above
} else {
// now rowcount = 3 ( top of new page for 3 )
// j is your x axis cell index ( j start from 0 on $.each function ) or you can add cellCount like rowCount and replace with
// rowcount is your y axis cell index
left = ( ( j ) * ( cellWidth + leftMargin );
top = ( ( rowcount - 3 ) * ( rowHeight + topMargin );
doc.cell( leftMargin, top, cellWidth, rowHeight, cellContent, i);
// 1st=left margin 2nd parameter=top margin, 3rd=row cell width 4th=Row height
}
}
You can convert html directly to pdf lossless. Youtube video for html => pdf example
html2canvas(element[0], {
onrendered: function (canvas) {
pages = Math.ceil(element[0].clientHeight / 1450);
for (i = 0; i <= pages; i += 1) {
if (i > 0) {
pdf.addPage();
}
srcImg = canvas;
sX = 0;
sY = 1450 * i;
sWidth = 1100;
sHeight = 1450;
dX = 0;
dY = 0;
dWidth = 1100;
dHeight = 1450;
window.onePageCanvas = document.createElement("canvas");
onePageCanvas.setAttribute('width', 1100);
onePageCanvas.setAttribute('height', 1450);
ctx = onePageCanvas.getContext('2d');
ctx.drawImage(srcImg, sX, sY, sWidth, sHeight, dX, dY, dWidth, dHeight);
canvasDataURL = onePageCanvas.toDataURL("image/png");
width = onePageCanvas.width;
height = onePageCanvas.clientHeight;
pdf.setPage(i + 1);
pdf.addImage(canvasDataURL, 'PNG', 35, 30, (width * 0.5), (height * 0.5));
}
pdf.save('testfilename.pdf');
}
});
var a = 0;
var d;
var increment;
for(n in array){
d = a++;
if(n % 6 === 0 && n != 0){
doc.addPage();
a = 1;
d = 0;
}
increment = d == 0 ? 10 : 50;
size = (d * increment) <= 0 ? 10 : d * increment;
doc.text(array[n], 10, size);
}

Custom Menu Script AssistanceNeeded

I am using a custom menu extension from Magento. I have one issue. There is a popup dropdown box that appears on the menu. When I use firebug to trace the coding I find this:
<div id="popup6" class="wp-custom-menu-popup" onmouseover="wpPopupOver(this, event, 'popup6', 'menu6')" onmouseout="wpHideMenuPopup(this, event, 'popup6', 'menu6')" style="display: none; top: 20px; left: 20px; z-index: 10000;">
I cannot find this code any where in the files from the extension so I tracked down this:
<script type="text/javascript">
//<![CDATA[
var CUSTOMMENU_POPUP_WIDTH = <?php echo Mage::getStoreConfig('custom_menu/popup/width') + 0; ?>;
var CUSTOMMENU_POPUP_TOP_OFFSET = <?php echo Mage::getStoreConfig('custom_menu/popup/top_offset') + 0; ?>;
var CUSTOMMENU_POPUP_DELAY_BEFORE_DISPLAYING = <?php echo Mage::getStoreConfig('custom_menu/popup/delay_displaying') + 0; ?>;
var CUSTOMMENU_POPUP_DELAY_BEFORE_HIDING = <?php echo Mage::getStoreConfig('custom_menu/popup/delay_hiding') + 0; ?>;
var CUSTOMMENU_RTL_MODE = <?php echo $_rtl; ?>;
var wpCustommenuTimerShow = {};
var wpCustommenuTimerHide = {};
//]]>
I need to change the top:20px where should I look for this? Its not in the js file and not in the css file... Cannot find it anywhere. Any ideas? I am a beginer! From my understanding it would have to be the JS file, I am not sure how to read it. JS is here:
function wpShowMenuPopup(objMenu, popupId)
{
if (typeof wpCustommenuTimerHide[popupId] != 'undefined') clearTimeout(wpCustommenuTimerHide[popupId]);
objMenu = $(objMenu.id); var popup = $(popupId); if (!popup) return;
wpCustommenuTimerShow[popupId] = setTimeout(function() {
popup.style.display = 'block';
objMenu.addClassName('active');
var popupWidth = CUSTOMMENU_POPUP_WIDTH;
if (!popupWidth) popupWidth = popup.getWidth();
var pos = wpPopupPos(objMenu, popupWidth);
popup.style.top = pos.top + 'px';
popup.style.left = pos.left + 'px';
wpSetPopupZIndex(popup);
if (CUSTOMMENU_POPUP_WIDTH)
popup.style.width = CUSTOMMENU_POPUP_WIDTH + 'px';
// --- Static Block width ---
var block2 = $(popupId).select('div.block2');
if (typeof block2[0] != 'undefined') {
var wStart = block2[0].id.indexOf('_w');
if (wStart > -1) {
var w = block2[0].id.substr(wStart+2);
} else {
var w = 0;
$(popupId).select('div.block1 div.column').each(function(item) {
w += $(item).getWidth();
});
}
//console.log(w);
if (w) block2[0].style.width = w + 'px';
}
}, CUSTOMMENU_POPUP_DELAY_BEFORE_DISPLAYING);
}
function wpHideMenuPopup(element, event, popupId, menuId)
{
if (typeof wpCustommenuTimerShow[popupId] != 'undefined') clearTimeout(wpCustommenuTimerShow[popupId]);
element = $(element.id); var popup = $(popupId); if (!popup) return;
var current_mouse_target = null;
if (event.toElement) {
current_mouse_target = event.toElement;
} else if (event.relatedTarget) {
current_mouse_target = event.relatedTarget;
}
wpCustommenuTimerHide[popupId] = setTimeout(function() {
if (!wpIsChildOf(element, current_mouse_target) && element != current_mouse_target) {
if (!wpIsChildOf(popup, current_mouse_target) && popup != current_mouse_target) {
popup.style.display = 'none';
$(menuId).removeClassName('active');
}
}
}, CUSTOMMENU_POPUP_DELAY_BEFORE_HIDING);
}
function wpPopupOver(element, event, popupId, menuId)
{
if (typeof wpCustommenuTimerHide[popupId] != 'undefined') clearTimeout(wpCustommenuTimerHide[popupId]);
}
function wpPopupPos(objMenu, w)
{
var pos = objMenu.cumulativeOffset();
var wraper = $('custommenu');
var posWraper = wraper.cumulativeOffset();
var xTop = pos.top - posWraper.top
if (CUSTOMMENU_POPUP_TOP_OFFSET) {
xTop += CUSTOMMENU_POPUP_TOP_OFFSET;
} else {
xTop += objMenu.getHeight();
}
var res = {'top': xTop};
if (CUSTOMMENU_RTL_MODE) {
var xLeft = pos.left - posWraper.left - w + objMenu.getWidth();
if (xLeft < 0) xLeft = 0;
res.left = xLeft;
} else {
var wWraper = wraper.getWidth();
var xLeft = pos.left - posWraper.left;
if ((xLeft + w) > wWraper) xLeft = wWraper - w;
if (xLeft < 0) xLeft = 0;
res.left = xLeft;
}
return res;
}
function wpIsChildOf(parent, child)
{
if (child != null) {
while (child.parentNode) {
if ((child = child.parentNode) == parent) {
return true;
}
}
}
return false;
}
function wpSetPopupZIndex(popup)
{
$$('.wp-custom-menu-popup').each(function(item){
item.style.zIndex = '9999';
});
popup.style.zIndex = '10000';
}
enter code here
There is an option in custom menu settings - top offset, may be this option defines top: 20px; attribute.

Google maps api v3 and UIWebView iOS memory issue

In my iOS app i want to display traffic information which is provided by google maps not by MKMapView..So i m using google maps api v3 but loading google maps api v3 maps in UIWebView causes memory leak.Specially when we zoom the Map and Click on satellite button.
Code --
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100%;}
#route_table { height: 0%;}
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=true">
</script>
<script type="text/javascript">
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
var arrayInput = [];
var trafficLayer;
var map;
var markers = [];
var bounds;
var zoomWidth;
var alertBOOL;
function initialize() {
var txt = new String(%#);
arrayInput = txt.split(',');
//var latlng = new google.maps.LatLng(parseFloat(arrayInput[0]),parseFloat(arrayInput[1]));
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 5,
center: latlng,
disableDefaultUI:true,
streetViewControl:false,
backgroundColor: '#FFFFF',
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
directionsDisplay.setMap(this.map);
directionsDisplay.suppressInfoWindows = true;
addTrafficButton();
addSatelliteButton();
calcRoute(arrayInput);
}
function calcRoute(inputArray) {
var i=0;
var wps = [];
var start;
var end;
var i = 0;
var j=0;
for(i=0;i<arrayInput.length-1;i=i+2)
{
if(i==0)
{
start = new google.maps.LatLng(parseFloat(arrayInput[i]),arrayInput[i+1]);
this.map.center = start;
}
else if(i==(arrayInput.length-2))
{
end = new google.maps.LatLng(parseFloat(arrayInput[i]),arrayInput[i+1]);
}
else
{
wps[j] = { location: new google.maps.LatLng(parseFloat(arrayInput[i]),arrayInput[i+1]) };
j++;
}
}
bounds = new google.maps.LatLngBounds(start,end);
this.map.fitBounds(bounds);
var request =
{
origin:start,
destination:end,
waypoints: wps,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(result, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections(result);
}
});
}
function addTrafficButton()
{
var tbutton = document.createElement("button");
tbutton.innerHTML = "Traffic On";
tbutton.style.position = "absolute";
tbutton.style.bottom = "50px";
tbutton.style.right = "15px";
tbutton.style.zIndex = 10;
tbutton.style.width = "70px";
tbutton.style.height = "30px";
this.map.getDiv().appendChild(tbutton);
tbutton.className = "lolight";
tbutton.onclick = function() {
if (tbutton.className == "hilight") {
tbutton.innerHTML = "Traffic On";
this.trafficLayer.setMap(null);
this.trafficLayer = null;
tbutton.className = "lolight";
} else {
tbutton.innerHTML = "Traffic Off";
this.trafficLayer = new google.maps.TrafficLayer();
this.trafficLayer.setMap(this.map);
tbutton.className = "hilight";
}
}
}
function addSatelliteButton()
{
var sbutton = document.createElement("button");
sbutton.innerHTML = "Satellite";
sbutton.style.position = "absolute";
sbutton.style.bottom = "90px";
sbutton.style.right = "15px";
sbutton.style.zIndex = 10;
sbutton.style.width = "70px";
sbutton.style.height = "30px";
this.map.getDiv().appendChild(sbutton);
sbutton.className = "lolight";
sbutton.onclick = function() {
if (sbutton.className == "hilight") {
sbutton.innerHTML = "Satellite";
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
sbutton.className = "lolight";
} else {
sbutton.innerHTML = "Map";
sbutton.className = "hilight";
map.setMapTypeId(google.maps.MapTypeId.HYBRID);
}
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%;"></div>
</body>
</html>
i think your issue can be solved using ARC into ios 5 .. it is best feature add by apple to into ios 5. it holds whole memory management into your app. Go with ARC it helps you lot.