Draw oval using Leafletjs Draw Library - javascript

I am trying to draw oval and Circle using Leafletjs Draw library, it works fine but the problem is the Circle boundary doesn't touch with the Mouse pointer on mousemove. here is the code and fiddle.
try to draw the oval you will observe the mouse pointer is not touching the circle boundary
https://jsfiddle.net/Lscupxqp/12/
var points = [L.GeoJSON.latLngToCoords(this._startLatLng),L.GeoJSON.latLngToCoords(latlng)];
var x = Math.abs(points[1][0] - points[0][0]);
var y = Math.abs(points[1][1] - points[0][1]);
var x_percent, y_percent;
x_percent = y_percent = 1;
//show in %
if(x < y) {
x_percent = x / y;
}
else {
y_percent = y / x;
}
this._drawShape(latlng);
this._shape.rx = x_percent;
this._shape.ry = y_percent;
GetPathString method
getPathString: function () {
var p = this._point,
r = this._radius;
if (this._checkIfEmpty()) {
return '';
}
//console.log(this);
if (L.Browser.svg) {
var rr = 'M' + p.x + ',' + (p.y - r) + 'A' + (r * this.rx) + ',' + (r * this.ry) + ',0,1,1,' + (p.x - 0.1) + ',' + (p.y - r) + ' z';
return rr;
} else {
p._round();
r = Math.round(r);
return 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r + ' 0,' + (65535 * 360);
}
}

It seems I've got your mistake - change (p.y - r) to (p.y - r * this.ry) :
if (L.Browser.svg) {
var rr = 'M' + p.x + ',' + (p.y - r * this.ry) +
'A' + (r * this.rx) + ',' + (r * this.ry) + ',0,0,0,' + p.x + ',' + (p.y + r * this.ry) +
'A' + (r * this.rx) + ',' + (r * this.ry) + ',0,1,0,' + (p.x) + ',' + (p.y - r * this.ry) +' z';

Related

How to change colors percent to RGB

I created my colors code 0-70 from green to red. Now, I want to change colors 0 - 70 from red to green.
function percentToRGB(percent) {
if (percent === 100) {
percent = 99
}
var r, g, b;
if (percent < 50) {
// green to yellow
r = Math.floor(255 * (percent / 50));
g = 255;
} else {
// yellow to red
r = 255;
g = Math.floor(255 * ((50 - percent % 50) / 50));
}
b = 0;
return "rgb(" + r + "," + g + "," + b + ")";
}
function render(i) {
var item = "<li style='background-color:" + percentToRGB(i) + "'>" + i + "</li>";
$("ul").append(item);
}
function repeat(fn, times) {
for (var i = 0; i < times; i++) fn(i);
}
repeat(render, 100);
li {
font-size:8px;
height:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>
You should just be able to switch the g and r variables around within the percentToRGB function. Here's a JSFiddle Link.
So the function would become:
function percentToRGB(percent) {
if (percent === 100) {
percent = 99
}
var r, g, b;
if (percent < 50) {
// green to yellow
g = Math.floor(255 * (percent / 50));
r = 255;
} else {
// yellow to red
g = 255;
r = Math.floor(255 * ((50 - percent % 50) / 50));
}
b = 0;
return "rgb(" + r + "," + g + "," + b + ")";
}

Pixel by pixel collision detection pinball

I'm currently working on a Pinball game using the HTML5 Canvas and JavaScript. Right now I'm getting a hard time with the pixel by pixel collision, which is fundamental because of the flippers.
Right now my Bounding Box Collision seems to be working
checkCollision(element) {
if (this.checkCollisionBoundingBox(element)) {
console.log("colision with the element bounding box");
if (this.checkCollisionPixelByPixel(element)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
checkCollisionBoundingBox(element) {
if (this.pos.x < element.pos.x + element.width && this.pos.x + this.width > element.pos.x && this.pos.y < element.pos.y + element.height && this.pos.y + this.height > element.pos.y) {
return true;
} else {
return false;
}
}
I've tried several ways of implementing the pixel by pixel one but for some reason it does not work perfectly (on walls, on images, on sprites etc). I'll leave them here:
checkCollisionPixelByPixel(element) {
var x_left = Math.floor(Math.max(this.pos.x, element.pos.x));
var x_right = Math.floor(Math.min(this.pos.x + this.width, element.pos.x + element.width));
var y_top = Math.floor(Math.max(this.pos.y, element.pos.y));
var y_bottom = Math.floor(Math.min(this.pos.y + this.height, element.pos.y + element.height));
for (var y = y_top; y < y_bottom; y++) {
for (var x = x_left; x < x_right; x++) {
var x_0 = Math.round(x - this.pos.x);
var y_0 = Math.round(y - this.pos.y);
var n_pix = y_0 * (this.width * this.total) + (this.width * (this.actual-1)) + x_0; //n pixel to check
var pix_op = this.imgData.data[4 * n_pix + 3]; //opacity (R G B A)
var element_x_0 = Math.round(x - element.pos.x);
var element_y_0 = Math.round(y - element.pos.y);
var element_n_pix = element_y_0 * (element.width * element.total) + (element.width * (element.actual-1)) + element_x_0; //n pixel to check
var element_pix_op = element.imgData.data[4 * element_n_pix + 3]; //opacity (R G B A)
console.log(element_pix_op);
if (pix_op == 255 && element_pix_op == 255) {
console.log("Colision pixel by pixel");
/*Debug*/
/*console.log("This -> (R:" + this.imgData.data[4 * n_pix] + ", G:" + this.imgData.data[4 * n_pix + 1] + ", B:" + this.imgData.data[4 * n_pix + 2] + ", A:" + pix_op + ")");
console.log("Element -> (R:" + element.imgData.data[4 * element_n_pix] + ", G:" + element.imgData.data[4 * element_n_pix + 1] + ", B:" + element.imgData.data[4 * element_n_pix + 2] + ", A:" + element_pix_op + ")");
console.log("Collision -> (x:" + x + ", y:" + y +")");
console.log("This(Local) -> (x:" + x_0 + ", y:" + y_0+")");
console.log("Element(Local) -> (x:" + element_x_0 + ", y:" + element_y_0+")");*/
/*ball vector*/
var vector = {
x: (x_0 - Math.floor(this.imgData.width / 2)),
y: -(y_0 - Math.floor(this.imgData.height / 2))
};
//console.log("ball vector -> ("+vector.x+", "+vector.y+") , Angulo: "+ Math.atan(vector.y/vector.x)* 180/Math.PI);
// THIS WAS THE FIRST TRY, IT DIDN'T WORK WHEN THE BALL WAS GOING NORTHEAST AND COLLIDED WITH A WALL. DIDN'T WORK AT ALL WITH SPRITES
//this.angle = (Math.atan2(vector.y, vector.x) - Math.PI) * (180 / Math.PI);
// THIS WAS THE SECOND ATTEMPT, WORKS WORSE THAN THE FIRST ONE :/
//normal vector
var normal = {
x: (x_0 - (this.imgData.width / 2)),
y: -(y_0 - (this.imgData.height / 2))
};
//Normalizar o vetor
var norm = Math.sqrt(normal.x * normal.x + normal.y * normal.y);
if (norm != 0) {
normal.x = normal.x / norm;
normal.y = normal.y / norm;
}
var n_rad = Math.atan2(normal.y, normal.x);
var n_deg = (n_rad + Math.PI) * 180 / Math.PI;
console.log("Vetor Normal -> (" + normal.x + ", " + normal.y + ") , Angulo: " + n_deg);
//Vetor Velocidade
var velocity = {
x: Math.cos((this.angle * Math.PI / 180) - Math.PI),
y: Math.sin((this.angle * Math.PI / 180) - Math.PI)
};
console.log("Vetor Velocidade -> (" + velocity.x + ", " + velocity.y + ") , Angulo: " + this.angle);
//Vetor Reflexao
var ndotv = normal.x * velocity.x + normal.y * velocity.y;
var reflection = {
x: -2 * ndotv * normal.x + velocity.x,
y: -2 * ndotv * normal.y + velocity.y
};
var r_rad = Math.atan2(reflection.y, reflection.x);
var r_deg = (r_rad + Math.PI) * 180 / Math.PI;
console.log("Vetor Reflexao -> (" + reflection.x + ", " + reflection.y + ") , Angulo: " + r_deg);
this.angle = r_deg;
return true;
}
}
}
return false;
}
}
The ball class
class Ball extends Element {
constructor(img, pos, width, height, n, sound, angle, speed) {
super(img, pos, width, height, n, sound);
this.angle = angle; //direction [0:360[
this.speed = speed;
}
move(ctx, cw, ch) {
var rads = this.angle * Math.PI / 180
var vx = Math.cos(rads) * this.speed / 60;
var vy = Math.sin(rads) * this.speed / 60;
this.pos.x += vx;
this.pos.y -= vy;
ctx.clearRect(0, 0, cw, ch);
this.draw(ctx, 1);
}
}
Assuming a "flipper" is composed of 2 arcs and 2 lines it would be much faster to do collision detection mathematically rather than by the much slower pixel-test method. Then you just need 4 math collision tests.
Even if your flippers are a bit more complicated than arcs+lines, the math hit tests would be "good enough" -- meaning in your fast-moving game, the user cannot visually notice the approximate math results vs the pixel-perfect results and the difference between the 2 types of tests will not affect gameplay at all. But the pixel-test version will take magnitudes more time and resources to accomplish. ;-)
First two circle-vs-circle collision tests:
function CirclesColliding(c1,c2){
var dx=c2.x-c1.x;
var dy=c2.y-c1.y;
var rSum=c1.r+c2.r;
return(dx*dx+dy*dy<=rSum*rSum);
}
Then two circle-vs-line-segment collision tests:
// [x0,y0] to [x1,y1] define a line segment
// [cx,cy] is circle centerpoint, cr is circle radius
function isCircleSegmentColliding(x0,y0,x1,y1,cx,cy,cr){
// calc delta distance: source point to line start
var dx=cx-x0;
var dy=cy-y0;
// calc delta distance: line start to end
var dxx=x1-x0;
var dyy=y1-y0;
// Calc position on line normalized between 0.00 & 1.00
// == dot product divided by delta line distances squared
var t=(dx*dxx+dy*dyy)/(dxx*dxx+dyy*dyy);
// calc nearest pt on line
var x=x0+dxx*t;
var y=y0+dyy*t;
// clamp results to being on the segment
if(t<0){x=x0;y=y0;}
if(t>1){x=x1;y=y1;}
return( (cx-x)*(cx-x)+(cy-y)*(cy-y) < cr*cr );
}

Is it possible to get v8 to internally inline a function?

I'm wondering if there is any way to get v8 to internally inline a function to speed up overall execution.
I have a simple function that returns the total energy of a pixel:
function pxEnergy(x, y) {
var tmp = (y * cols + x - 1) * 4
return (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3];
}
I'm calling this ~96,000,000 times and my code takes ~2 sec to run.
If I inline the function 8 times in my loops, e.g.:
xSum += -2 * (tmp = (y * cols + x - 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
The same code now takes ~500ms to run. But it's ugly as sin :)
So I'm wondering if anyone has any magic tricks up their sleeves to get the same speedup without manually inlining the function.
[edit] full code per request:
generateEnergyMap() {
// woo-hoo, nothing to do!
if (!this.dirty) { return Promise.resolve(); }
var energyMap = this.energyMap = [];
var cols = this.width;
var rows = this.height;
var data = this.data;
var pxEnergy = new Function('data', 'cols', 'x', 'y', 'var ix = (y * cols + x) * 4; return (data[ix] + data[ix + 1] + data[ix + 2]) * data[ix + 3]');
return this.imgPromise.then(function() {
for (var y = 0; y < rows; y++) {
energyMap.push([]);
for (var x = 0; x < cols; x++) {
var up = y;
var down = y < (rows - 1);
var left = x;
var right = x < (cols - 1);
var tmp;
var xSum = 0;
var ySum = 0;
if (left) {
xSum += -2 * pxEnergy(data, cols, x - 1, y); // (tmp = (y * cols + x - 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
if (up) {
xSum += tmp = -1 * pxEnergy(data, cols, x - 1, y - 1); // (tmp = ((y - 1) * cols + x - 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
ySum += tmp;
}
if (down) {
xSum += -1 * (tmp = pxEnergy(data, cols, x - 1, y + 1)); // (tmp = (tmp = ((y + 1) * cols + x - 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]));
ySum += tmp;
}
}
if (right) {
xSum += 2 * pxEnergy(data, cols, x + 1, y); // (tmp = (y * cols + x + 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
if (up) {
xSum += tmp = pxEnergy(data, cols, x + 1, y - 1); // (tmp = ((y - 1) * cols + x + 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
ySum += -1 * tmp;
}
if (down) {
xSum += tmp = pxEnergy(data, cols, x + 1, y + 1); // (tmp = ((y + 1) * cols + x + 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
ySum += tmp;
}
}
if (up) {
ySum += -2 * pxEnergy(data, cols, x, y - 1); // (tmp = ((y - 1) * cols + x) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
}
if (down) {
ySum += 2 * pxEnergy(data, cols, x, y + 1); // (tmp = ((y + 1) * cols + x) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
}
energyMap[y].push(Math.sqrt(xSum * xSum + ySum * ySum));
}
}
});
}

Combine multiple rotation in matrix

I would like to use this JavaScript matrix library: Matrix3D
My target is to implement a function which takes the CSS transform properties as arguments and returns with the proper matrix3d() CSS transform declaration.
function 3d(x, y, z, rotateX, rotateY, rotateZ){
var m = Matrix3D.create();
Matrix3D.translateX(m, x);
Matrix3D.translateY(m, y);
Matrix3D.translateZ(m, z);
Matrix3D.rotateX(m,this.data.rotateX);
Matrix3D.rotateY(m,this.data.rotateY);
Matrix3D.rotateZ(m,this.data.rotateZ);
return Matrix3D.toTransform3D(m);
}
It works fine for the x,y,z and the rotateZ parameters, but it is unable to merge the rotation matrices into one matrix, instead it overwrites the rotation.
Could you help me how should I combine matrices to behave in the right way?
UPDATE #1
I just found out that I should need to create a quaternion from the three euler rotation axis. euler to quaternion
function eulerToQuaternion(rotateX, rotateY, rotateZ) {
// Assuming the angles are in radians.
var c1 = Math.cos(rotateX / 2),
s1 = Math.sin(rotateX / 2),
c2 = Math.cos(rotateY / 2),
s2 = Math.sin(rotateY / 2),
c3 = Math.cos(rotateZ / 2),
s3 = Math.sin(rotateZ / 2),
c1c2 = c1 * c2,
s1s2 = s1 * s2,
w = c1c2 * c3 - s1s2 * s3,
x = c1c2 * s3 + s1s2 * c3,
y = s1 * c2 * c3 + c1 * s2 * s3,
z = c1 * s2 * c3 - s1 * c2 * s3;
return [w, x, y, z]
}
function deg2rad(deg) {
return deg * (Math.PI / 180);
};
console.log(eulerToQuaternion(deg2rad(45), 0, deg2rad(45)));
But here I'm stuck again. How can I add this quaternion to my matrix?
Found the solution:
function a(x, y, z, scaleX, scaleY, rotateX, rotateY, rotateZ) {
var D = 2;
var Y = Math.cos(rotateX * (Math.PI / 180)).toFixed(D),
Z = Math.sin(rotateX * (Math.PI / 180)).toFixed(D),
b = Math.cos(rotateY * (Math.PI / 180)).toFixed(D),
F = Math.sin(rotateY * (Math.PI / 180)).toFixed(D),
I = Math.cos(rotateZ * (Math.PI / 180)).toFixed(D),
P = Math.sin(rotateZ * (Math.PI / 180)).toFixed(D);
var a = new Array(16);
a[0] = b * I * scaleX;
a[1] = -1 * P;
a[2] = F;
a[3] = 0;
a[4] = P;
a[5] = Y * I * scaleY;
a[6] = Z;
a[7] = 0;
a[8] = -1 * F;
a[9] = -1 * Z;
a[10] = b * Y;
a[11] = 0;
a[12] = x;
a[13] = y;
a[14] = z;
a[15] = 1;
console.log("transform: matrix3d(" + a[0] + "," + a[1] + "," + a[2] + "," + a[3] + "," + a[4] + "," + a[5] + "," + a[6] + "," + a[7] + "," + a[8] + "," + a[9] + "," + a[10] + "," + a[11] + "," + a[12] + "," + a[13] + "," + a[14] + "," + a[15] + ");");
}
What about passing 2 parameters to the Matrix3D.rotateXYZ() method like below
Matrix3D.rotateX(m, this.data.rotateX)
I don't know which version you are using, but that method needs 2 parameters according to https://gist.github.com/f5io/7466669.
If you omit the first parameter, this.data.rotateX will be understood as a result array, not a rotation, and this is not what you wanted to do.

Executing a function after animate settimeout

Found this on stack overflow the other day http://codepen.io/anon/pen/LERrGG.
I think this is a great pen that could be really useful. The only problem is that there is no ability to call a function after the timer runs out. I was trying to implement this with no success.
How do I edit the code so that it becomes a useful timer i.e. it 'runs out'?
(function animate() {
theta += 0.5;
theta %= 360;
var x = Math.sin(theta * Math.PI / 180) * radius;
var y = Math.cos(theta * Math.PI / 180) * -radius;
var d = 'M0,0 v' + -radius + 'A' + radius + ',' + radius + ' 1 ' + ((theta > 180) ? 1 : 0) + ',1 ' + x + ',' + y + 'z';
timer.setAttribute('d', d);
setTimeout(animate, t)
})();
You can determine that a complete circle has been painted by checking to see if theta ends up smaller than when it started out:
(function animate() {
var oldTheta = theta;
theta += 0.5;
theta %= 360;
if (theta < oldTheta) {
// the timer has "run out"
}
else {
var x = Math.sin(theta * Math.PI / 180) * radius;
var y = Math.cos(theta * Math.PI / 180) * -radius;
var d = 'M0,0 v' + -radius + 'A' + radius + ',' + radius + ' 1 ' + ((theta > 180) ? 1 : 0) + ',1 ' + x + ',' + y + 'z';
timer.setAttribute('d', d);
setTimeout(animate, t);
}
})();
you have to check if theta smaller than 360.
(function animate() {
theta += 0.5;
var x = Math.sin(theta * Math.PI / 180) * radius;
var y = Math.cos(theta * Math.PI / 180) * -radius;
var d = 'M0,0 v' + -radius + 'A' + radius + ',' + radius + ' 1 ' + ((theta > 180) ? 1 : 0) + ',1 ' + x + ',' + y + 'z';
timer.setAttribute('d', d);
if(theta<360) setTimeout(animate, t);
else doSomething();
})();

Categories