How to set zoom focus based on pinch location using hammer.js - javascript

I am able to perform pinch for div content when passing the element to the method below, but whilst the pinch is performing the focus is always at the center.
How can I change the focus based on pinch location?
function hammerIt(elm) {
hammertime = new Hammer(elm, {});
hammertime.get('pinch').set({
enable: true
});
var posX = 0,
posY = 0,
scale = 1,
last_scale = 1,
last_posX = 0,
last_posY = 0,
max_pos_x = 0,
max_pos_y = 0,
transform = "",
el = elm;
hammertime.on('doubletap pan pinch panend pinchend', function(ev) {
if (ev.type == "doubletap") {
transform =
"translate3d(0, 0, 0) " +
"scale3d(2, 2, 1) ";
scale = 2;
last_scale = 2;
try {
if (window.getComputedStyle(el, null).getPropertyValue('-webkit-transform').toString() != "matrix(1, 0, 0, 1, 0, 0)") {
transform =
"translate3d(0, 0, 0) " +
"scale3d(1, 1, 1) ";
scale = 1;
last_scale = 1;
}
} catch (err) {}
el.style.webkitTransform = transform;
transform = "";
}
//pan
if (scale != 1) {
posX = last_posX + ev.deltaX;
posY = last_posY + ev.deltaY;
max_pos_x = Math.ceil((scale - 1) * el.clientWidth / 2);
max_pos_y = Math.ceil((scale - 1) * el.clientHeight / 2);
if (posX > max_pos_x) {
posX = max_pos_x;
}
if (posX < -max_pos_x) {
posX = -max_pos_x;
}
if (posY > max_pos_y) {
posY = max_pos_y;
}
if (posY < -max_pos_y) {
posY = -max_pos_y;
}
}
//pinch
if (ev.type == "pinch") {
scale = Math.max(.999, Math.min(last_scale * (ev.scale), 4));
}
if(ev.type == "pinchend"){last_scale = scale;}
//panend
if(ev.type == "panend"){
last_posX = posX < max_pos_x ? posX : max_pos_x;
last_posY = posY < max_pos_y ? posY : max_pos_y;
}
if (scale != 1) {
transform =
"translate3d(" + posX + "px," + posY + "px, 0) " +
"scale3d(" + scale + ", " + scale + ", 1)";
}
if (transform) {
el.style.webkitTransform = transform;
}
});
}

Related

How to change opacity in Javascript for object

Found code here for metaballs using vanilla javascript. Is there a way I can change the opacity of the metaballs? I think it should be a quick fix but im not too sure. I tried changing to CSS class bubbles but that didnt work so im assuming in needs to be in the Javascript. Anything helps, thanks.
Found code here for metaballs using vanilla javascript. Is there a way I can change the opacity of the metaballs? I think it should be a quick fix but im not too sure. I tried changing to CSS class bubbles but that didnt work so im assuming in needs to be in the Javascript. Anything helps, thanks.
;(function() {
"use strict";
var lava0;
var ge1doot = {
screen: {
elem: null,
callback: null,
ctx: null,
width: 0,
height: 0,
left: 0,
top: 0,
init: function (id, callback, initRes) {
this.elem = document.getElementById(id);
this.callback = callback || null;
if (this.elem.tagName == "CANVAS") this.ctx = this.elem.getContext("2d");
window.addEventListener('resize', function () {
this.resize();
}.bind(this), false);
this.elem.onselectstart = function () { return false; }
this.elem.ondrag = function () { return false; }
initRes && this.resize();
return this;
},
resize: function () {
var o = this.elem;
this.width = o.offsetWidth;
this.height = o.offsetHeight;
for (this.left = 0, this.top = 0; o != null; o = o.offsetParent) {
this.left += o.offsetLeft;
this.top += o.offsetTop;
}
if (this.ctx) {
this.elem.width = this.width;
this.elem.height = this.height;
}
this.callback && this.callback();
}
}
}
// Point constructor
var Point = function(x, y) {
this.x = x;
this.y = y;
this.magnitude = x * x + y * y;
this.computed = 0;
this.force = 0;
};
Point.prototype.add = function(p) {
return new Point(this.x + p.x, this.y + p.y);
};
// Ball constructor
var Ball = function(parent) {
var min = .1;
var max = 1.5;
this.vel = new Point(
(Math.random() > 0.5 ? 1 : -1) * (0.2 + Math.random() * 0.25), (Math.random() > 0.5 ? 1 : -1) * (0.2 + Math.random())
);
this.pos = new Point(
parent.width * 0.2 + Math.random() * parent.width * 0.6,
parent.height * 0.2 + Math.random() * parent.height * 0.6
);
this.size = (parent.wh / 15) + ( Math.random() * (max - min) + min ) * (parent.wh / 15);
this.width = parent.width;
this.height = parent.height;
};
// move balls
Ball.prototype.move = function() {
// bounce borders
if (this.pos.x >= this.width - this.size) {
if (this.vel.x > 0) this.vel.x = -this.vel.x;
this.pos.x = this.width - this.size;
} else if (this.pos.x <= this.size) {
if (this.vel.x < 0) this.vel.x = -this.vel.x;
this.pos.x = this.size;
}
if (this.pos.y >= this.height - this.size) {
if (this.vel.y > 0) this.vel.y = -this.vel.y;
this.pos.y = this.height - this.size;
} else if (this.pos.y <= this.size) {
if (this.vel.y < 0) this.vel.y = -this.vel.y;
this.pos.y = this.size;
}
// velocity
this.pos = this.pos.add(this.vel);
};
// lavalamp constructor
var LavaLamp = function(width, height, numBalls, c0, c1) {
this.step = 5;
this.width = width;
this.height = height;
this.wh = Math.min(width, height);
this.sx = Math.floor(this.width / this.step);
this.sy = Math.floor(this.height / this.step);
this.paint = false;
this.metaFill = createRadialGradient(width, height, width, c0, c1);
this.plx = [0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0];
this.ply = [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1];
this.mscases = [0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 0, 2, 1, 1, 0];
this.ix = [1, 0, -1, 0, 0, 1, 0, -1, -1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1];
this.grid = [];
this.balls = [];
this.iter = 0;
this.sign = 1;
// init grid
for (var i = 0; i < (this.sx + 2) * (this.sy + 2); i++) {
this.grid[i] = new Point(
(i % (this.sx + 2)) * this.step, (Math.floor(i / (this.sx + 2))) * this.step
)
}
// create metaballs
for (var k = 0; k < numBalls; k++) {
this.balls[k] = new Ball(this);
}
};
// compute cell force
LavaLamp.prototype.computeForce = function(x, y, idx) {
var force;
var id = idx || x + y * (this.sx + 2);
if (x === 0 || y === 0 || x === this.sx || y === this.sy) {
force = 0.6 * this.sign;
} else {
force = 0;
var cell = this.grid[id];
var i = 0;
var ball;
while (ball = this.balls[i++]) {
force += ball.size * ball.size / (-2 * cell.x * ball.pos.x - 2 * cell.y * ball.pos.y + ball.pos.magnitude + cell.magnitude);
}
force *= this.sign
}
this.grid[id].force = force;
return force;
};
// compute cell
LavaLamp.prototype.marchingSquares = function(next) {
var x = next[0];
var y = next[1];
var pdir = next[2];
var id = x + y * (this.sx + 2);
if (this.grid[id].computed === this.iter) {
return false;
}
var dir, mscase = 0;
// neighbors force
for (var i = 0; i < 4; i++) {
var idn = (x + this.ix[i + 12]) + (y + this.ix[i + 16]) * (this.sx + 2);
var force = this.grid[idn].force;
if ((force > 0 && this.sign < 0) || (force < 0 && this.sign > 0) || !force) {
// compute force if not in buffer
force = this.computeForce(
x + this.ix[i + 12],
y + this.ix[i + 16],
idn
);
}
if (Math.abs(force) > 1) mscase += Math.pow(2, i);
}
if (mscase === 15) {
// inside
return [x, y - 1, false];
} else {
// ambiguous cases
if (mscase === 5) dir = (pdir === 2) ? 3 : 1;
else if (mscase === 10) dir = (pdir === 3) ? 0 : 2;
else {
// lookup
dir = this.mscases[mscase];
this.grid[id].computed = this.iter;
}
// draw line
var ix = this.step / (
Math.abs(Math.abs(this.grid[(x + this.plx[4 * dir + 2]) + (y + this.ply[4 * dir + 2]) * (this.sx + 2)].force) - 1) /
Math.abs(Math.abs(this.grid[(x + this.plx[4 * dir + 3]) + (y + this.ply[4 * dir + 3]) * (this.sx + 2)].force) - 1) + 1
);
ctx.lineTo(
this.grid[(x + this.plx[4 * dir]) + (y + this.ply[4 * dir]) * (this.sx + 2)].x + this.ix[dir] * ix,
this.grid[(x + this.plx[4 * dir + 1]) + (y + this.ply[4 * dir + 1]) * (this.sx + 2)].y + this.ix[dir + 4] * ix
);
this.paint = true;
// next
return [
x + this.ix[dir + 4],
y + this.ix[dir + 8],
dir
];
}
};
LavaLamp.prototype.renderMetaballs = function() {
var i = 0, ball;
while (ball = this.balls[i++]) ball.move();
// reset grid
this.iter++;
this.sign = -this.sign;
this.paint = false;
ctx.fillStyle = this.metaFill;
ctx.beginPath();
// compute metaballs
i = 0;
//ctx.shadowBlur = 50;
//ctx.shadowColor = "green";
while (ball = this.balls[i++]) {
// first cell
var next = [
Math.round(ball.pos.x / this.step),
Math.round(ball.pos.y / this.step), false
];
// marching squares
do {
next = this.marchingSquares(next);
} while (next);
// fill and close path
if (this.paint) {
ctx.fill();
ctx.closePath();
ctx.beginPath();
this.paint = false;
}
}
};
// gradients
var createRadialGradient = function(w, h, r, c0, c1) {
var gradient = ctx.createRadialGradient(
w / 1, h / 1, 0,
w / 1, h / 1, r
);
gradient.addColorStop(0, c0);
gradient.addColorStop(1, c1);
};
// main loop
var run = function() {
requestAnimationFrame(run);
ctx.clearRect(0, 0, screen.width, screen.height);
lava0.renderMetaballs();
};
// canvas
var screen = ge1doot.screen.init("bubble", null, true),
ctx = screen.ctx;
screen.resize();
// create LavaLamps
lava0 = new LavaLamp(screen.width, screen.height, 6, "#FF9298", "#E4008E");
run();
})();
body {
margin: 0;
}
.wrap {
overflow: hidden;
position: relative;
height: 100vh;
}
canvas {
width: 100%;
height: 100%;
}
<div class="wrap">
<canvas id="bubble"></canvas>
</div>
You can do it by changing the context alpha channel with RGBA (see at the very bottom ctx.fillStyle = 'rgba(0, 0, 255, 0.5)' // NEW! where 0.5 is the level of opacity - see ) :
;
(function() {
'use strict'
var lava0
var ge1doot = {
screen: {
elem: null,
callback: null,
ctx: null,
width: 0,
height: 0,
left: 0,
top: 0,
init: function(id, callback, initRes) {
this.elem = document.getElementById(id)
this.callback = callback || null
if (this.elem.tagName == 'CANVAS') this.ctx = this.elem.getContext('2d')
window.addEventListener(
'resize',
function() {
this.resize()
}.bind(this),
false
)
this.elem.onselectstart = function() {
return false
}
this.elem.ondrag = function() {
return false
}
initRes && this.resize()
return this
},
resize: function() {
var o = this.elem
this.width = o.offsetWidth
this.height = o.offsetHeight
for (this.left = 0, this.top = 0; o != null; o = o.offsetParent) {
this.left += o.offsetLeft
this.top += o.offsetTop
}
if (this.ctx) {
this.elem.width = this.width
this.elem.height = this.height
}
this.callback && this.callback()
},
},
}
// Point constructor
var Point = function(x, y) {
this.x = x
this.y = y
this.magnitude = x * x + y * y
this.computed = 0
this.force = 0
}
Point.prototype.add = function(p) {
return new Point(this.x + p.x, this.y + p.y)
}
// Ball constructor
var Ball = function(parent) {
var min = 0.1
var max = 1.5
this.vel = new Point(
(Math.random() > 0.5 ? 1 : -1) * (0.2 + Math.random() * 0.25),
(Math.random() > 0.5 ? 1 : -1) * (0.2 + Math.random())
)
this.pos = new Point(
parent.width * 0.2 + Math.random() * parent.width * 0.6,
parent.height * 0.2 + Math.random() * parent.height * 0.6
)
this.size = parent.wh / 15 + (Math.random() * (max - min) + min) * (parent.wh / 15)
this.width = parent.width
this.height = parent.height
}
// move balls
Ball.prototype.move = function() {
// bounce borders
if (this.pos.x >= this.width - this.size) {
if (this.vel.x > 0) this.vel.x = -this.vel.x
this.pos.x = this.width - this.size
} else if (this.pos.x <= this.size) {
if (this.vel.x < 0) this.vel.x = -this.vel.x
this.pos.x = this.size
}
if (this.pos.y >= this.height - this.size) {
if (this.vel.y > 0) this.vel.y = -this.vel.y
this.pos.y = this.height - this.size
} else if (this.pos.y <= this.size) {
if (this.vel.y < 0) this.vel.y = -this.vel.y
this.pos.y = this.size
}
// velocity
this.pos = this.pos.add(this.vel)
}
// lavalamp constructor
var LavaLamp = function(width, height, numBalls, c0, c1) {
this.step = 5
this.width = width
this.height = height
this.wh = Math.min(width, height)
this.sx = Math.floor(this.width / this.step)
this.sy = Math.floor(this.height / this.step)
this.paint = false
this.metaFill = createRadialGradient(width, height, width, c0, c1)
this.plx = [0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0]
this.ply = [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1]
this.mscases = [0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 0, 2, 1, 1, 0]
this.ix = [1, 0, -1, 0, 0, 1, 0, -1, -1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1]
this.grid = []
this.balls = []
this.iter = 0
this.sign = 1
// init grid
for (var i = 0; i < (this.sx + 2) * (this.sy + 2); i++) {
this.grid[i] = new Point((i % (this.sx + 2)) * this.step, Math.floor(i / (this.sx + 2)) * this.step)
}
// create metaballs
for (var k = 0; k < numBalls; k++) {
this.balls[k] = new Ball(this)
}
}
// compute cell force
LavaLamp.prototype.computeForce = function(x, y, idx) {
var force
var id = idx || x + y * (this.sx + 2)
if (x === 0 || y === 0 || x === this.sx || y === this.sy) {
force = 0.6 * this.sign
} else {
force = 0
var cell = this.grid[id]
var i = 0
var ball
while ((ball = this.balls[i++])) {
force +=
(ball.size * ball.size) /
(-2 * cell.x * ball.pos.x - 2 * cell.y * ball.pos.y + ball.pos.magnitude + cell.magnitude)
}
force *= this.sign
}
this.grid[id].force = force
return force
}
// compute cell
LavaLamp.prototype.marchingSquares = function(next) {
var x = next[0]
var y = next[1]
var pdir = next[2]
var id = x + y * (this.sx + 2)
if (this.grid[id].computed === this.iter) {
return false
}
var dir,
mscase = 0
// neighbors force
for (var i = 0; i < 4; i++) {
var idn = x + this.ix[i + 12] + (y + this.ix[i + 16]) * (this.sx + 2)
var force = this.grid[idn].force
if ((force > 0 && this.sign < 0) || (force < 0 && this.sign > 0) || !force) {
// compute force if not in buffer
force = this.computeForce(x + this.ix[i + 12], y + this.ix[i + 16], idn)
}
if (Math.abs(force) > 1) mscase += Math.pow(2, i)
}
if (mscase === 15) {
// inside
return [x, y - 1, false]
} else {
// ambiguous cases
if (mscase === 5) dir = pdir === 2 ? 3 : 1
else if (mscase === 10) dir = pdir === 3 ? 0 : 2
else {
// lookup
dir = this.mscases[mscase]
this.grid[id].computed = this.iter
}
// draw line
var ix =
this.step /
(Math.abs(
Math.abs(this.grid[x + this.plx[4 * dir + 2] + (y + this.ply[4 * dir + 2]) * (this.sx + 2)].force) - 1
) /
Math.abs(
Math.abs(this.grid[x + this.plx[4 * dir + 3] + (y + this.ply[4 * dir + 3]) * (this.sx + 2)].force) - 1
) +
1)
ctx.lineTo(
this.grid[x + this.plx[4 * dir] + (y + this.ply[4 * dir]) * (this.sx + 2)].x + this.ix[dir] * ix,
this.grid[x + this.plx[4 * dir + 1] + (y + this.ply[4 * dir + 1]) * (this.sx + 2)].y + this.ix[dir + 4] * ix
)
this.paint = true
// next
return [x + this.ix[dir + 4], y + this.ix[dir + 8], dir]
}
}
LavaLamp.prototype.renderMetaballs = function() {
var i = 0,
ball
while ((ball = this.balls[i++])) ball.move()
// reset grid
this.iter++
this.sign = -this.sign
this.paint = false
ctx.fillStyle = this.metaFill
ctx.beginPath()
// compute metaballs
i = 0
//ctx.shadowBlur = 50;
//ctx.shadowColor = "green";
while ((ball = this.balls[i++])) {
// first cell
var next = [Math.round(ball.pos.x / this.step), Math.round(ball.pos.y / this.step), false]
// marching squares
do {
next = this.marchingSquares(next)
} while (next)
// fill and close path
if (this.paint) {
ctx.fill()
ctx.closePath()
ctx.beginPath()
this.paint = false
}
}
}
// gradients
var createRadialGradient = function(w, h, r, c0, c1) {
var gradient = ctx.createRadialGradient(w / 1, h / 1, 0, w / 1, h / 1, r)
gradient.addColorStop(0, c0)
gradient.addColorStop(1, c1)
}
// main loop
var run = function() {
requestAnimationFrame(run)
ctx.clearRect(0, 0, screen.width, screen.height)
ctx.fillStyle = 'rgba(0, 0, 255, 0.5)' // NEW!
lava0.renderMetaballs()
}
// canvas
var screen = ge1doot.screen.init('bubble', null, true),
ctx = screen.ctx
screen.resize()
// create LavaLamps
lava0 = new LavaLamp(screen.width, screen.height, 6, '#FF9298', '#E4008E')
run()
})()
body {
margin: 0;
}
.wrap {
overflow: hidden;
position: relative;
height: 100vh;
}
canvas {
width: 100%;
height: 100%;
}
<div class="wrap">
<canvas id="bubble"></canvas>
</div>
Your Lava constructor takes two colors, these can be modified to fit your color needs. By using rgba() versions of your colors, you can set the alpha (ie the opacity) or your bubbles/meatballs. However, before you do that, you need to return the gradient created in createRadialGradient so that the colors can be used:
var createRadialGradient = function(w, h, r, c0, c1) {
// ... code ...
return gradient; // add this line
};
Now you can modify how you call your constructor:
// rgba versions of your colors -----------------------\/
lava0 = new LavaLamp(screen.width, screen.height, 6, "rgba(255, 146, 152, 0.5)", "rgba(228, 0, 142, 0.5)");
;(function() {
"use strict";
var lava0;
var ge1doot = {
screen: {
elem: null,
callback: null,
ctx: null,
width: 0,
height: 0,
left: 0,
top: 0,
init: function (id, callback, initRes) {
this.elem = document.getElementById(id);
this.callback = callback || null;
if (this.elem.tagName == "CANVAS") this.ctx = this.elem.getContext("2d");
window.addEventListener('resize', function () {
this.resize();
}.bind(this), false);
this.elem.onselectstart = function () { return false; }
this.elem.ondrag = function () { return false; }
initRes && this.resize();
return this;
},
resize: function () {
var o = this.elem;
this.width = o.offsetWidth;
this.height = o.offsetHeight;
for (this.left = 0, this.top = 0; o != null; o = o.offsetParent) {
this.left += o.offsetLeft;
this.top += o.offsetTop;
}
if (this.ctx) {
this.elem.width = this.width;
this.elem.height = this.height;
}
this.callback && this.callback();
}
}
}
// Point constructor
var Point = function(x, y) {
this.x = x;
this.y = y;
this.magnitude = x * x + y * y;
this.computed = 0;
this.force = 0;
};
Point.prototype.add = function(p) {
return new Point(this.x + p.x, this.y + p.y);
};
// Ball constructor
var Ball = function(parent) {
var min = .1;
var max = 1.5;
this.vel = new Point(
(Math.random() > 0.5 ? 1 : -1) * (0.2 + Math.random() * 0.25), (Math.random() > 0.5 ? 1 : -1) * (0.2 + Math.random())
);
this.pos = new Point(
parent.width * 0.2 + Math.random() * parent.width * 0.6,
parent.height * 0.2 + Math.random() * parent.height * 0.6
);
this.size = (parent.wh / 15) + ( Math.random() * (max - min) + min ) * (parent.wh / 15);
this.width = parent.width;
this.height = parent.height;
};
// move balls
Ball.prototype.move = function() {
// bounce borders
if (this.pos.x >= this.width - this.size) {
if (this.vel.x > 0) this.vel.x = -this.vel.x;
this.pos.x = this.width - this.size;
} else if (this.pos.x <= this.size) {
if (this.vel.x < 0) this.vel.x = -this.vel.x;
this.pos.x = this.size;
}
if (this.pos.y >= this.height - this.size) {
if (this.vel.y > 0) this.vel.y = -this.vel.y;
this.pos.y = this.height - this.size;
} else if (this.pos.y <= this.size) {
if (this.vel.y < 0) this.vel.y = -this.vel.y;
this.pos.y = this.size;
}
// velocity
this.pos = this.pos.add(this.vel);
};
// lavalamp constructor
var LavaLamp = function(width, height, numBalls, c0, c1) {
this.step = 5;
this.width = width;
this.height = height;
this.wh = Math.min(width, height);
this.sx = Math.floor(this.width / this.step);
this.sy = Math.floor(this.height / this.step);
this.paint = false;
this.metaFill = createRadialGradient(width, height, width, c0, c1);
this.plx = [0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0];
this.ply = [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1];
this.mscases = [0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 0, 2, 1, 1, 0];
this.ix = [1, 0, -1, 0, 0, 1, 0, -1, -1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1];
this.grid = [];
this.balls = [];
this.iter = 0;
this.sign = 1;
// init grid
for (var i = 0; i < (this.sx + 2) * (this.sy + 2); i++) {
this.grid[i] = new Point(
(i % (this.sx + 2)) * this.step, (Math.floor(i / (this.sx + 2))) * this.step
)
}
// create metaballs
for (var k = 0; k < numBalls; k++) {
this.balls[k] = new Ball(this);
}
};
// compute cell force
LavaLamp.prototype.computeForce = function(x, y, idx) {
var force;
var id = idx || x + y * (this.sx + 2);
if (x === 0 || y === 0 || x === this.sx || y === this.sy) {
force = 0.6 * this.sign;
} else {
force = 0;
var cell = this.grid[id];
var i = 0;
var ball;
while (ball = this.balls[i++]) {
force += ball.size * ball.size / (-2 * cell.x * ball.pos.x - 2 * cell.y * ball.pos.y + ball.pos.magnitude + cell.magnitude);
}
force *= this.sign
}
this.grid[id].force = force;
return force;
};
// compute cell
LavaLamp.prototype.marchingSquares = function(next) {
var x = next[0];
var y = next[1];
var pdir = next[2];
var id = x + y * (this.sx + 2);
if (this.grid[id].computed === this.iter) {
return false;
}
var dir, mscase = 0;
// neighbors force
for (var i = 0; i < 4; i++) {
var idn = (x + this.ix[i + 12]) + (y + this.ix[i + 16]) * (this.sx + 2);
var force = this.grid[idn].force;
if ((force > 0 && this.sign < 0) || (force < 0 && this.sign > 0) || !force) {
// compute force if not in buffer
force = this.computeForce(
x + this.ix[i + 12],
y + this.ix[i + 16],
idn
);
}
if (Math.abs(force) > 1) mscase += Math.pow(2, i);
}
if (mscase === 15) {
// inside
return [x, y - 1, false];
} else {
// ambiguous cases
if (mscase === 5) dir = (pdir === 2) ? 3 : 1;
else if (mscase === 10) dir = (pdir === 3) ? 0 : 2;
else {
// lookup
dir = this.mscases[mscase];
this.grid[id].computed = this.iter;
}
// draw line
var ix = this.step / (
Math.abs(Math.abs(this.grid[(x + this.plx[4 * dir + 2]) + (y + this.ply[4 * dir + 2]) * (this.sx + 2)].force) - 1) /
Math.abs(Math.abs(this.grid[(x + this.plx[4 * dir + 3]) + (y + this.ply[4 * dir + 3]) * (this.sx + 2)].force) - 1) + 1
);
ctx.lineTo(
this.grid[(x + this.plx[4 * dir]) + (y + this.ply[4 * dir]) * (this.sx + 2)].x + this.ix[dir] * ix,
this.grid[(x + this.plx[4 * dir + 1]) + (y + this.ply[4 * dir + 1]) * (this.sx + 2)].y + this.ix[dir + 4] * ix
);
this.paint = true;
// next
return [
x + this.ix[dir + 4],
y + this.ix[dir + 8],
dir
];
}
};
LavaLamp.prototype.renderMetaballs = function() {
var i = 0, ball;
while (ball = this.balls[i++]) ball.move();
// reset grid
this.iter++;
this.sign = -this.sign;
this.paint = false;
ctx.fillStyle = this.metaFill;
ctx.beginPath();
// compute metaballs
i = 0;
//ctx.shadowBlur = 50;
//ctx.shadowColor = "green";
while (ball = this.balls[i++]) {
// first cell
var next = [
Math.round(ball.pos.x / this.step),
Math.round(ball.pos.y / this.step), false
];
// marching squares
do {
next = this.marchingSquares(next);
} while (next);
// fill and close path
if (this.paint) {
ctx.fill();
ctx.closePath();
ctx.beginPath();
this.paint = false;
}
}
};
// gradients
var createRadialGradient = function(w, h, r, c0, c1) {
var gradient = ctx.createRadialGradient(
w / 1, h / 1, 0,
w / 1, h / 1, r
);
gradient.addColorStop(0, c0);
gradient.addColorStop(1, c1);
return gradient;
};
// main loop
var run = function() {
requestAnimationFrame(run);
ctx.clearRect(0, 0, screen.width, screen.height);
lava0.renderMetaballs();
};
// canvas
var screen = ge1doot.screen.init("bubble", null, true),
ctx = screen.ctx;
screen.resize();
// create LavaLamps
lava0 = new LavaLamp(screen.width, screen.height, 6, "rgba(255, 146, 152, 0.5)", "rgba(228, 0, 142, 0.5)");
run();
})();
body {
margin: 0;
}
.wrap {
overflow: hidden;
position: relative;
height: 100vh;
}
canvas {
width: 100%;
height: 100%;
}
<div class="wrap">
<canvas id="bubble"></canvas>
</div>

How to zoom image with angularJS

How can i zoom the image when i click on the image itself using angularJS. I cant happen to do it when i using this website given: https://github.com/owlsomely/angular-image-zoom?utm_source=angular-js.in&utm_medium=website&utm_campaign=content-curation . Anyone can help?
My js file:
var camListApp = angular.module('camListApp', ['ui.bootstrap'])
camListApp.filter('unique', function() {
return function(input, key) {
var unique = {};
var uniqueList = [];
for(var i = 0; i < input.length; i++){
if(typeof unique[input[i][key]] == "undefined"){
unique[input[i][key]] = "";
uniqueList.push(input[i]);
}
}
return uniqueList;
};
});
camListApp.controller("Hello", ["$scope", "$http", function($scope, $http){
$scope.custom = true;
$scope.toggleCustom = function(url) {
$scope.custom = ! $scope.custom;
$scope.imageView = url;
};
$http.get('http://localhost:8082/camera/list').then(function(response) {
console.log(response);
$scope.records= response.data;
});
}]);
My html file:
<div ng-controller="Hello" class="col-xs-12">
<b>Search:</b><br>
<input type = "text" ng-model="searchBox" uib-typeahead="state.cameraid as state.cameraid for state in records | filter:searchBox | limitTo:8 | unique:'cameraid'">
<br>
<br>
<br>
<br>
<table border = 1 class="table table-striped table-hover" style="width:45%">
<thead>
<tr>
<th><center>CamID</th></center>
<th><center>Timestamp</th></center>
<th><center>View Image</center></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="record in records | filter:searchBox | orderBy:'+timestamp'">
<td>{{record.cameraid}}</td>
<td>{{record.timestamp}}</td>
<td><center> <button class="btn btn-primary" ng-click="toggleCustom(record.filename)" onclick="myFunction()">View</center></button></td>
</tr>
</tbody>
</table>
<span id="myDIV" ng-hide="custom">
<img ng-src="http://localhost:9100/Images/{{imageView}}.png" image-zoom width="500" height="400">
</span>
<!--<span ng-hide="custom">To:
<input type="text" id="to" />
</span>-->
<span ng-show="custom"></span>
</div>
<script>
function myFunction() {
document.getElementById("myDIV").style.position = "absolute";
}
</script>
</body>
</html>
Created ng-click on image
HTML
<span id="myDIV" ng-hide="custom">
<img id="view" ng-src="http://www.w3schools.com/css/{{imageView}}" width="300" height="300" ng-click="zoom()">
</span>
JS
$scope.zoom = function() {
var imageId = document.getElementById('view');
if(imageId.style.width == "400px"){
imageId.style.width = "300px";
imageId.style.height = "300px";
}else{
imageId.style.width = "400px";
imageId.style.height = "400px";
}
Codepen- http://codepen.io/nagasai/pen/jrMzER
my simple directive to increase the image reduction and image movement. I hope will be useful to you.
(function () {
angular
.module('app')
.directive('zoom', [function () {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
var img = elem[0];
$(img).css({
"position": "absolute",
"top": "0",
"bottom": "0",
"left": "0",
"right": "0",
"margin": "auto",
"padding-left": "1px",
"padding-right": "1px",
"padding-top": "1px",
"padding-bottom": "1px",
"-webkit - user - select": "none",
"-webkit - user - drag": "none"
});
var imageContainer = img.parentNode.parentNode;
$(imageContainer).css({
"text-align": "center",
"margin": "0",
"padding": "0",
"height": "100%",
"max- height": "100%",
"width": "100%",
"background-color": "#000",
"overflow": "hidden",
"-webkit - user - select": "none",
"cursor": "context - menu",
});
var parent = img.parentNode;
$(parent).css({
"width": "100%",
"height": "auto",
"margin": 0,
"padding": 0,
"display": "-webkit - box",
"-webkit - box - pack": "center",
"-webkit - box - align": "center",
"z-index": "5"
});
var currentScale = 1;
var currentRotation = 90
let transformOriginX = 0, transformOriginY = 0;
let translateX = 0, translateY = 0;
function setTransformOrigin() {
let imgRect = img.getBoundingClientRect();
let parentRect = parent.getBoundingClientRect();
let visibleWidth = (imgRect.width > parent.offsetWidth) ? imgRect.left + parentRect.width : imgRect.width;
let visibleHeight = (imgRect.height > parent.offsetHeight) ? imgRect.top + parentRect.height : imgRect.height;
let beginX = parentRect.right - visibleWidth, beginY = parentRect.bottom - visibleHeight;
let endX = beginX + visibleWidth, endY = beginY + visibleHeight;
let midX = beginX + ((endX - beginX) / 2), midY = beginY + ((endY - beginY) / 2);
// if (midY > imageContainer.clientHeight / 2) midY = imageContainer.clientHeight / 2;
//if (midX > imageContainer.clientWidth / 2) midX = imageContainer.clientWidth / 2;
if (midY > imageContainer.clientHeight / 2) { parent.style.transformOrigin = midX + 'px ' + midY + 'px' } else {
parent.style.transformOrigin = midX + 'px ' + imageContainer.clientHeight / 2 + 'px'
}
}
function scaleImage(scale, event) {
img.style.transform = 'scale(' + scale + ') ' + 'rotate(' + (currentRotation - 90) + 'deg)';
if (scale < currentScale) {
let imgRect = img.getBoundingClientRect();
let imageContainerRect = imageContainer.getBoundingClientRect();
if (parent.style.transform.match('translate')) {
let parentTransform = parent.style.transform.replace('translate(', '').replace(')', '').split(', ');
let moveX = parentTransform[0].replace('px', ''), moveY = parentTransform[1].replace('px', '');
if ((imageContainerRect.right - imgRect.right) > 0 || (imageContainerRect.left - imgRect.left) < 0) {
let moveBy = ((imageContainerRect.right - imgRect.right) > 0) ? (imageContainerRect.right - imgRect.right) : (imageContainerRect.left - imgRect.left);
moveX = (imgRect.width > parent.offsetWidth) ? (parseFloat(parentTransform[0]) + moveBy) : 0;
transformOriginX = (transformOriginX - moveBy);
}
if ((imageContainerRect.bottom - imgRect.bottom) > 0 || (imageContainerRect.top - imgRect.top) < 0) {
let moveBy = ((imageContainerRect.bottom - imgRect.bottom) > 0) ? (imageContainerRect.bottom - imgRect.bottom) : (imageContainerRect.top - imgRect.top);
moveY = (imgRect.height > parent.offsetHeight) ? (parseFloat(parentTransform[1]) + moveBy) : 0;
transformOriginY = (transformOriginY + moveBy);
}
if (scale <= 1) { translateX = 0; translateY = 0; }
parent.style.transformOrigin = transformOriginX + 'px ' + transformOriginY + 'px';
}
}
currentScale = scale;
let imgRect = img.getBoundingClientRect();
let parentRect = parent.getBoundingClientRect();
let overflow_horizontal = (imgRect.width > parent.offsetWidth ? true : false);
let overflow_vertical = (imgRect.height > parent.offsetHeight ? true : false);
let startX = event.pageX - translateX, startY = event.pageY - translateY;
let max_left = parentRect.left - imgRect.left;
let max_top = parentRect.top - imgRect.top;
var evt = window.event;
translateX = (Math.abs(evt.pageX - startX) >= max_left ? (max_left * Math.sign(evt.pageX - startX)) : (evt.pageX - startX));
translateY = (Math.abs(evt.pageY - startY) >= max_top ? (max_top * Math.sign(evt.pageY - startY)) : (evt.pageY - startY));
translateX = overflow_horizontal ? translateX : 0, translateY = overflow_vertical ? translateY : 0;
if ((translateX != 0) && (translateY != 0)) {
if (translateY > imageContainer.clientHeight/2) { parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + translateY + 'px)' } else {
parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + imageContainer.clientHeight / 2+'px)'
}
} else {
parent.style['-webkit-transform'] = ''
};
return false;
}
function tap() {
let imgRect = img.getBoundingClientRect();
let parentRect = parent.getBoundingClientRect();
let overflow_horizontal = (imgRect.width > parent.offsetWidth ? true : false);
let overflow_vertical = (imgRect.height > parent.offsetHeight ? true : false);
let startX = event.pageX - translateX, startY = event.pageY - translateY;
let max_left = parentRect.left - imgRect.left;
let max_top = parentRect.top - imgRect.top;
var evt = window.event;
translateX = (Math.abs(evt.pageX - startX) >= max_left ? (max_left * Math.sign(evt.pageX - startX)) : (evt.pageX - startX));
translateY = (Math.abs(evt.pageY - startY) >= max_top ? (max_top * Math.sign(evt.pageY - startY)) : (evt.pageY - startY));
translateX = overflow_horizontal ? translateX : 0, translateY = overflow_vertical ? translateY : 0;
if ((translateX != 0) && (translateY != 0)) {
if (translateY > imageContainer.clientHeight / 2) {
parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + translateY + 'px)'
} else {
parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + imageContainer.clientHeight / 2+ 'px)'
}
} else {
parent.style['-webkit-transform'] = ''
};
}
function makeDraggable(event) {
parent = img.parentNode;
imageContainer = img.parentNode.parentNode;
$(parent).css({
"display": "-webkit - box",
"-webkit - box - pack": "center",
"-webkit - box - align": "center",
"z-index": "5"
});
$(imageContainer).css({
"text-align": "center",
"margin": "0",
"padding": "0",
"overflow": "hidden",
"-webkit - user - select": "none",
"cursor": "context - menu",
});
let imgRect = img.getBoundingClientRect();
let parentRect =parent.getBoundingClientRect();
let overflow_horizontal = (imgRect.width > parent.offsetWidth ? true : false);
let overflow_vertical = (imgRect.height > parent.offsetHeight ? true : false);
let startX = event.pageX - translateX, startY = event.pageY - translateY;
let max_left = parentRect.left - imgRect.left;
let max_top = parentRect.top - imgRect.top;
window.onmousemove = function (evt) {
if (evt == null) { evt = window.event; }
translateX = (Math.abs(evt.pageX - startX) >= max_left ? (max_left * Math.sign(evt.pageX - startX)) : (evt.pageX - startX));
translateY = (Math.abs(evt.pageY - startY) >= max_top ? (max_top * Math.sign(evt.pageY - startY)) : (evt.pageY - startY));
translateX = overflow_horizontal ? translateX : 0, translateY = overflow_vertical ? translateY : 0;
if ((translateX != 0) && (translateY != 0)) {
if (translateY > imageContainer.clientHeight) {
parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + translateY + 'px)'
} else {
parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + imageContainer.clientHeight / 2+ 'px)'
}
} else {
parent.style['-webkit-transform'] = ''
};
return false;
}
window.onmouseup = function (evt) {
setTransformOrigin();
window.onmousemove = null;
}
return false;
};
img.addEventListener('mousedown', function () { makeDraggable(event); });
elem.bind('mousewheel', function (e) {
var img = e.currentTarget.style.width;
var scaleX = e.currentTarget.getBoundingClientRect().width / e.currentTarget.offsetWidth;
var w = "";
var resW = "";
var resL = "";
var resT = "";
var zValue = 1.2;
var newScale = scaleX * zValue;
var newScale = "scale(1)";
var val = parseInt(w.replace('%', ''));
if (e.originalEvent.wheelDelta / 120 > 0) {
newScale = scaleX * zValue;
}
else {
if ((scaleX / zValue) > 1) {
newScale = scaleX / zValue
} else {
newScale = 1.0;
}
}
scaleImage(newScale, e);
setTransformOrigin();
window.onmousemove = null;
});
}
}
}]);
})();
Use at HTML as
<image zoom src="" ></image>

Why isn't the location of my img not changing past 10px?

I want an img to follow the mouse, but it doesn't seem to do it.
It stops after it moves 10px.
I don't know why it's not working. When I set the position of the img to the position of the mouse, it works.
var elem = document.getElementById("img").style;
var IE = document.all ? true : false
if (!IE) document.captureEvents(Event.MOUSEMOVE)
var tempX;
var tempY;
function getMouseXY(e) {
if (IE) {
tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;
} else {
tempX = e.pageX;
tempY = e.pageY;
}
if (tempX < 0) {
tempX = 0;
}
if (tempY < 0) {
tempY = 0;
}
document.Show.MouseX.value = tempX;
document.Show.MouseY.value = tempY;
return true;
}
document.onmousemove = getMouseXY;
document.onmouseover = update;
elem.left = "0px";
elem.bottom = "0px";
elem.position = "relative";
function update() {
if (parseInt(elem.left) < (tempX - 10)) {
elem.left = (parseInt(elem.left) + 1, 10).toString() + "px";
console.log((parseInt(elem.left) + 1, 10).toString() + "px");
}
if (parseInt(elem.left) > (tempX - 10)) {
elem.left = (parseInt(elem.left) - 1, 10).toString() + "px";
console.log((parseInt(elem.left) - 1, 10).toString() + "px");
}
if (parseInt(elem.bottom) < (-tempY + 50)) {
elem.bottom = (parseInt(elem.bottom) + 1, 10).toString() + "px";
console.log((parseInt(elem.left) + 1, 10).toString() + "px");
}
if (parseInt(elem.bottom) > (-tempY + 50)) {
elem.bottom = (parseInt(elem.bottom) - 1, 10).toString() + "px";
console.log((parseInt(elem.left) + 1, 10).toString() + "px");
}
}
<img id="img" src="//placehold.it/20.png">

using querySelectorAll to move more than one div

I'm trying to use the queryselectorall to be able to move more than one div, but I'm getting trouble for not knowing how to adapt. I thought of using a while that style:
[].forEach.call(els, function(el) {
...
});
But not got success, how can I fix my script to make it work?
My code:
var draggableEl = document.querySelectorAll('[data-drag]'), magnet = document.querySelector('.magnet-zone');
function isOverlapping(el1, el2) {
var rect1 = el1.getBoundingClientRect(), rect2 = el2.getBoundingClientRect();
return !(rect1.top > rect2.bottom || rect1.right < rect2.left || rect1.bottom < rect2.top || rect1.left > rect2.right);
}
function moveToPos(x, y) {
var el = draggableEl;
el.style.transform = 'translate(' + Math.round(x, 10) + 'px, ' + Math.round(y, 10) + 'px) translateZ(0)';
el.style.webkitTransform = 'translate(' + Math.round(x, 10) + 'px, ' + Math.round(y, 10) + 'px) translateZ(0)';
}
function moveMagnet(x, y) {
var dist = 12, width = $('body').width() / 2, height = $('body').height(), direction = x > width ? 1 : -1, percX = x > width ? (x - width) / width : -(width - x) / width, percY = Math.min(1, (height - y) / (height / 2));
magnet.style.marginLeft = Math.round(dist / 1.5 * percX) + 'px';
magnet.style.marginBottom = Math.round(dist * percY) + 'px';
}
function move(event) {
var el = draggableEl, magnetRect = magnet.getBoundingClientRect(), elRect = el.getBoundingClientRect();
x = this._posOrigin.x + event.pageX - this._touchOrigin.x;
y = this._posOrigin.y + event.pageY - this._touchOrigin.y;
moveMagnet(x + elRect.width / 2, y + elRect.height / 2);
$('body').addClass('moving');
var touchPos = {
top: y,
right: x + elRect.width,
bottom: y + elRect.height,
left: x
};
overlapping = !(touchPos.top > magnetRect.bottom || touchPos.right < magnetRect.left || touchPos.bottom < magnetRect.top || touchPos.left > magnetRect.right);
if (overlapping) {
var mx = magnetRect.width / 2 + magnetRect.left;
var my = magnetRect.height / 2 + magnetRect.top;
x = mx - elRect.width / 2;
y = my - elRect.height / 2;
if (!$(el).hasClass('overlap')) {
$(el).addClass('transition');
setTimeout(function () {
$(el).removeClass('transition');
}, 150);
setTimeout(function () {
el.remove();
setTimeout(function () {
$('body').removeClass('moving touching');
}, 900);
}, 1000);
}
magnet.className = magnet.className.replace(' overlap', '') + ' overlap';
el.className = el.className.replace(' overlap', '') + ' overlap';
} else {
if ($(el).hasClass('transition')) {
$(el).removeClass('transition');
}
if ($(el).hasClass('overlap')) {
$(el).addClass('transition');
setTimeout(function () {
$(el).removeClass('transition');
}, 100);
}
magnet.className = magnet.className.replace(' overlap', '');
el.className = el.className.replace(' overlap', '');
}
moveToPos(x, y);
}
$(draggableEl).on('touchstart mousedown', onTouchStart).on('touchmove drag', move).on('touchend mouseup', onTouchEnd);
function onTouchStart(event) {
var rect = this.getBoundingClientRect();
$('body').addClass('touching');
$(this).removeClass('edge transition');
this._touchOrigin = {
x: event.pageX,
y: event.pageY
};
this._posOrigin = {
x: rect.left,
y: rect.top
};
}
function onTouchEnd(event) {
var el = draggableEl, rect = el.getBoundingClientRect(), width = $('body').width(), halfScreen = width / 2;
if (!$(el).hasClass('overlap')) {
$('body').removeClass('moving touching');
magnet.style.marginBottom = magnet.style.marginLeft = '0px';
var x = rect.left + rect.width / 2 < halfScreen ? +10 : width - 10 - rect.width;
$(el).addClass('edge');
moveToPos(x, rect.top);
setTimeout(function () {
$(el).removeClass('edge');
}, 500);
}
}
source: http://jsfiddle.net/4yt1roa6/

hammer drag center

I'm using Hammers library for my app. How can I drag my element from any point that I touch and not by center ? thanks !
var hammertime = Hammer(document.getElementById('contentTab'), {
transform_always_block:true,
transform_min_scale: 1,
drag_block_horizontal: true,
drag_block_vertical: true,
drag_min_distance: 0,
drag_max_touches: 2,
release: false
});
var rect = document.getElementById('tabella');
var posX=0, posY=0,
scale=1, last_scale,
rotation= 1, last_rotation,
dt =0;
hammertime.on('touch doubletap drag transform', function(ev) {
switch(ev.type) {
case 'doubletap':
if (dt == 0){
dt=1;
scale = 2;
}else if (dt ==1){
dt = 0;
scale = 1;
posX=0;
posY=0;
}
last_rotation = rotation;
break;
case 'touch':
last_scale = scale;
last_rotation = rotation;
break;
case 'drag':
posX = ev.gesture.deltaX;
posY = ev.gesture.deltaY;
break;
case 'transform':
// rotation = last_rotation + ev.gesture.rotation;
scale = Math.max(1, Math.min(last_scale * ev.gesture.scale, 10));
break;
}
// transform!
var transform =
"translate3d("+posX+"px,"+posY+"px, 0) " +
"scale3d("+scale+","+scale+", 0) " ;
"rotate("+rotation+"deg) ";
rect.style.transform = transform;
rect.style.oTransform = transform;
rect.style.msTransform = transform;
rect.style.mozTransform = transform;
rect.style.webkitTransform = transform;
});
Changing
posX = ev.gesture.deltaX;
posY = ev.gesture.deltaY;
to
posX += ev.gesture.deltaX;
posY += ev.gesture.deltaY;
might do the trick.

Categories

Resources