Pure Javascript How to Zoom Image on mousemove? - javascript

I'm trying to create onmousemove event inside the image then show the zoomed image in the right side.
Problem:
When I try to mousemove inside the image, the black box and zoomed image are blinking.
The zoomed image is not match in the blackbox.
How do I do that? May computation is wrong.
This is my code.
<div>
<div id="cursor" style="background:black; opacity:0.5; width:100px; height:100px; position:absolute; display:none">
</div>
<div style="float:left;">
<img id="img" src="http://www.animenewsnetwork.com/thumbnails/cover400x200/cms/news/102950/26902290903_3c8f2db0ea_b.jpg" onmousemove="getPos(event)" onmouseout="stopTracking()"/>
</div>
<div id="zoom" style="width:300px; height:300px; zoom:1; float:left;">
qwe
</div>
</div>
<script>
function getPos(e){
var x = e.clientX;
var y = e.clientY;
var width = document.getElementById("img").clientWidth;
var height = document.getElementById("img").clientHeight;
document.getElementById("cursor").style.left = x - 50;
document.getElementById("cursor").style.top = y - 50;
document.getElementById("cursor").style.display = "inline-block";
document.getElementById("zoom").style.background = "url('http://www.animenewsnetwork.com/thumbnails/cover400x200/cms/news/102950/26902290903_3c8f2db0ea_b.jpg') "+x / width * 100+"% "+y / width * 100+"%";
}
function stopTracking(){
document.getElementById("cursor").style.display = "none";
document.getElementById("zoom").style.background = "transparent";
}
</script>

I added time delay of half a second, the blinking is gone.
function getPos(e){
var delay=500; //1/2 second
setTimeout(function() {
//your code to be executed after 1/2 second
var x = e.clientX;
var y = e.clientY;
var width = document.getElementById("img").clientWidth;
var height = document.getElementById("img").clientHeight;
document.getElementById("cursor").style.left = x - 50;
document.getElementById("cursor").style.top = y - 50;
document.getElementById("cursor").style.display = "inline-block";
document.getElementById("zoom").style.background = "url('http://www.animenewsnetwork.com/thumbnails/cover400x200/cms/news/102950/26902290903_3c8f2db0ea_b.jpg') "+x / width * 100+"% "+y / width * 100+"%";
}, delay);
}

catch source from my e-commerce project (i'm using GSAP library for animation u can create custom CSS class with transitions instead):
<div class="grid col-10 rel z300">
<div class="border padt20 padb20 padl20 padr20 zoom--in flex align-center">
<img class="auto" src="img/prod.jpg" data-zoom="img/prod-large.jpg" alt="">
</div>
</div>
export class zoom_in_gallery {
constructor() {
if (!this.setVars()) return;
this.setEvents();
}
setVars() {
let _this = this;
_this.zoom = document.body.getElementsByTagName('section')[0].getElementsByClassName('zoom--in')[0];
if (!this.zoom) return false;
_this.img = this.zoom.firstElementChild;
if (!this.img) return false;
_this.zoom_pop = false;
_this.act = false;
return true;
}
setEvents() {
let _this = this;
function del(el) => {
el = typeof el === 'string' ? document.body.getElementsByClassName(el)[0] : el;
if (!el || !el.parentNode) return;
return el.parentNode.removeChild(el);
}
this.obj.onmove = (e) => {
if (_this.act) return;
let y = e.offsetY ? (e.offsetY) : e.pageY - _this.img.offsetTop,
x = e.offsetX ? (e.offsetX) : e.pageX - _this.img.offsetLeft;
if (!_this.zoom_pop) {
_this.zoom_pop = _this.render(e.target.parentNode, `<div class="top0 right0 abs o-hidden border" style="right:calc(-70%);left:initial;height:${_this.zoom.offsetWidth / 1.5}px;width:${_this.zoom.offsetWidth / 1.5}px"><div style="width:100%;height:100%;background: #fff url(${_this.img.dataset.zoom}) 0 0 / cover scroll no-repeat"></div></div>`);
TweenLite.fromTo(_this.zoom_pop, .3, {autoAlpha: 0}, {autoAlpha: 1});
}
_this.zoom_pop.firstElementChild.style.backgroundPosition = `${x / 3.8}% ${y / 3.8}%`;
};
this.obj.onleave = () => {
if (!_this.zoom_pop || _this.act) return;
_this.act = true;
TweenLite.to(_this.zoom_pop, .3, {
autoAlpha: 0, onComplete: () => {
del(_this.zoom_pop);
_this.zoom_pop = false;
_this.act = false;
}
});
};
this.zoom.addEventListener('mousemove', this.obj.onmove);
this.zoom.addEventListener('mouseout', this.obj.onleave);
}
render(relEl, tpl, cfg = {}) {
if (!relEl) return;
const parse = typeof cfg.parse === 'undefined' ? true : cfg.parse, child;
if (tpl.nodeName === 'TEMPLATE') {
child = document.importNode(tpl.content, true);
} else if (typeof tpl === 'string') {
const range = document.createRange();
range.selectNode(relEl);
child = range.createContextualFragment(tpl);
} else {
child = tpl;
}
if (parse) {
relEl.appendChild(child);
return relEl.lastElementChild;
}
return {rel: relEl, el: child};
}
}

Related

Random movement of circles created by the script

I have a function that craeates divs with a circle.
Now they are all created and appear at the beginning of the page and go further in order.
Next, I need each circle to appear in a random place. I did this.
Now I need all of them to move randomly across the entire page, I have difficulties with this.
Here is an example of how everything works for one element that is already on the page.
https://jsfiddle.net/quej8wko/
But when I add this code, all my created circles don't move.
I get an error:
"message": "Uncaught TypeError: Cannot set properties of null (setting 'willChange')",
This is probably due to the fact that initially there are no circles on the page. How can I connect the code so that all created circles move?
//creating circles
var widthHeight = 40; // <-- circle width
var margin = 20; // <-- margin - is it necessary ?
var delta = widthHeight + margin;
function createDiv(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
// Get the random positions minus the delta
currentTop = Math.floor(Math.random() * documentHeight) - delta;
currentLeft = Math.floor(Math.random() * documentWidth) - delta;
// Keep the positions between -20px and the current positions
var limitedTop = Math.max(margin * -1, currentTop);
var limitedLeft = Math.max(margin * -1, currentLeft);
div.style.top = limitedTop + "px";
div.style.left = limitedLeft + "px";
document.body.appendChild(div);
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`)
}, oneSecond);
//move circles
function RandomObjectMover(obj, container) {
this.$object = obj;
this.$container = container;
this.container_is_window = container === window;
this.pixels_per_second = 250;
this.current_position = { x: 0, y: 0 };
this.is_running = false;
}
// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
this.pixels_per_second = pxPerSec;
}
RandomObjectMover.prototype._getContainerDimensions = function() {
if (this.$container === window) {
return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
} else {
return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
}
}
RandomObjectMover.prototype._generateNewPosition = function() {
// Get container dimensions minus div size
var containerSize = this._getContainerDimensions();
var availableHeight = containerSize.height - this.$object.clientHeight;
var availableWidth = containerSize.width - this.$object.clientHeight;
// Pick a random place in the space
var y = Math.floor(Math.random() * availableHeight);
var x = Math.floor(Math.random() * availableWidth);
return { x: x, y: y };
}
RandomObjectMover.prototype._calcDelta = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dist = Math.sqrt( dx*dx + dy*dy );
return dist;
}
RandomObjectMover.prototype._moveOnce = function() {
// Pick a new spot on the page
var next = this._generateNewPosition();
// How far do we have to move?
var delta = this._calcDelta(this.current_position, next);
// Speed of this transition, rounded to 2DP
var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
//console.log(this.current_position, next, delta, speed);
this.$object.style.transition='transform '+speed+'s linear';
this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
// Save this new position ready for the next call.
this.current_position = next;
};
RandomObjectMover.prototype.start = function() {
if (this.is_running) {
return;
}
// Make sure our object has the right css set
this.$object.willChange = 'transform';
this.$object.pointerEvents = 'auto';
this.boundEvent = this._moveOnce.bind(this)
// Bind callback to keep things moving
this.$object.addEventListener('transitionend', this.boundEvent);
// Start it moving
this._moveOnce();
this.is_running = true;
}
RandomObjectMover.prototype.stop = function() {
if (!this.is_running) {
return;
}
this.$object.removeEventListener('transitionend', this.boundEvent);
this.is_running = false;
}
// Init it
var x = new RandomObjectMover(document.querySelector(".circle"), window);
// Start it off
x.start();
.circle {
clip-path: circle(50%);
height: 40px;
width: 40px;
margin: 20px;
position: absolute;
}
I have modified the snippet which works as you expected.
There was a mistake where you were initializing and creating the object instance only once and none of the div elements that you created inside the setInterval function never got Instantiated.
I think you are just starting out with JavaScript with this sample project.
Below are few suggestions:
Learn to debug the code. You should be using dev tools by making use of debugger statement where it takes you to the source code to analyze the variable scope and stack during the runtime. console.log also helps in few situations.
I could see a lot of confusing naming convention (You have named the create div parameter as id but creating a div class using that id)
Try using ES6 features (class syntax is really good when writing OOP in JS although it's just a syntactic sugar for prototype)
//creating circles
var widthHeight = 40; // <-- circle width
var margin = 20; // <-- margin - is it necessary ?
var delta = widthHeight + margin;
function createAndInitializeDivObject(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
// Get the random positions minus the delta
currentTop = Math.floor(Math.random() * documentHeight) - delta;
currentLeft = Math.floor(Math.random() * documentWidth) - delta;
// Keep the positions between -20px and the current positions
var limitedTop = Math.max(margin * -1, currentTop);
var limitedLeft = Math.max(margin * -1, currentLeft);
div.style.top = limitedTop + "px";
div.style.left = limitedLeft + "px";
document.body.appendChild(div);
var x = new RandomObjectMover(document.querySelector(`.${id}`), window);
x.start();
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i += 1;
createAndInitializeDivObject(`circle${i}`)
}, oneSecond);
//move circles
function RandomObjectMover(obj, container) {
this.$object = obj;
this.$container = container;
this.container_is_window = container === window;
this.pixels_per_second = 250;
this.current_position = { x: 0, y: 0 };
this.is_running = false;
}
// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
this.pixels_per_second = pxPerSec;
}
RandomObjectMover.prototype._getContainerDimensions = function() {
if (this.$container === window) {
return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
} else {
return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
}
}
RandomObjectMover.prototype._generateNewPosition = function() {
// Get container dimensions minus div size
var containerSize = this._getContainerDimensions();
var availableHeight = containerSize.height - this.$object.clientHeight;
var availableWidth = containerSize.width - this.$object.clientHeight;
// Pick a random place in the space
var y = Math.floor(Math.random() * availableHeight);
var x = Math.floor(Math.random() * availableWidth);
return { x: x, y: y };
}
RandomObjectMover.prototype._calcDelta = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dist = Math.sqrt( dx*dx + dy*dy );
return dist;
}
RandomObjectMover.prototype._moveOnce = function() {
// Pick a new spot on the page
var next = this._generateNewPosition();
// How far do we have to move?
var delta = this._calcDelta(this.current_position, next);
// Speed of this transition, rounded to 2DP
var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
//console.log(this.current_position, next, delta, speed);
this.$object.style.transition='transform '+speed+'s linear';
this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
// Save this new position ready for the next call.
this.current_position = next;
};
RandomObjectMover.prototype.start = function() {
if (this.is_running) {
return;
}
// Make sure our object has the right css set
this.$object.willChange = 'transform';
this.$object.pointerEvents = 'auto';
this.boundEvent = this._moveOnce.bind(this)
// Bind callback to keep things moving
this.$object.addEventListener('transitionend', this.boundEvent);
// Start it moving
this._moveOnce();
this.is_running = true;
}
RandomObjectMover.prototype.stop = function() {
if (!this.is_running) {
return;
}
this.$object.removeEventListener('transitionend', this.boundEvent);
this.is_running = false;
}
// Init it
var x = new RandomObjectMover(document.querySelector(".circle"), window);
// Start it off
x.start();
.circle {
width: 35px;
height: 35px;
border-radius: 35px;
background-color: #ffffff;
border: 3px solid purple;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="circle"></div>
<script src="app.js"></script>
</body>
</html>

Constraints problem with HTML element drag

I made script for dragging element around my react application in the way that limits are parent container. I achieved what I want but not in the way I want. I want when I reach limits to block that axis from trying to go further to avoid this annoying effect of script calculating and returning div in position.
const drag = (id) => {
const element = document.getElementById(id);
const parent = element.parentNode;
let newState = { x: 0, y: 0 };
let oldState = { x: 0, y: 0 };
const dragElement = (e) => {
e = e || window.event;
e.preventDefault();
oldState.x = e.clientX;
oldState.y = e.clientY;
document.onmouseup = stopDrag;
document.onmousemove = startDrag;
};
const startDrag = (e) => {
e = e || window.event;
e.preventDefault();
newState.x = oldState.x - e.clientX;
newState.y = oldState.y - e.clientY;
oldState.x = e.clientX;
oldState.y = e.clientY;
const handleX = () => {
let x = 0;
if (element.offsetLeft < 0) {
x = 0;
} else if (element.offsetLeft + element.offsetWidth > parent.offsetWidth) {
x = parent.offsetWidth - element.offsetWidth;
} else {
x = element.offsetLeft - newState.x;
}
return `${x}px`;
};
const handleY = () => {
let y = 0;
if (element.offsetTop < 0) {
y = 0;
} else if (element.offsetTop + element.offsetHeight > parent.offsetHeight) {
y = parent.offsetHeight - element.offsetHeight;
} else {
y = element.offsetTop - newState.y;
}
return `${y}px`;
};
element.style.top = handleY();
element.style.left = handleX();
};
const stopDrag = () => {
document.onmouseup = null;
document.onmousemove = null;
};
if (document.getElementById(element.id + "Header")) {
document.getElementById(element.id + "Header").onmousedown = dragElement;
} else {
element.onmousedown = dragElement;
}
};
drag("test");
.parent {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
inset: 16px;
background: red;
}
.draggable {
position: absolute;
width: 50px;
height: 50px;
background: green;
}
<div class="parent">
<div class="draggable" id="test"></div>
</div>

4 animated SVGs in one HTML file using Animate CC

http://christianluneborg.com/dev/animation/icon-global.html
How do I load 4 separated animated SVGs in one JS/HTML files exported from Animate CC? I have created 1 animated SVG and it exports 3 different JS in one HTML. Is there a way I can reuse JS for other 3 icon SVGs without messing up the code? I know its not a good practice to load a bunch of JS files for each animated SVGs.
Just for 1 animated SVG (JS)
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<script src="icon-skyscrapers.js"></script>
<script>
var canvas, stage, exportRoot, anim_container, dom_overlay_container,
fnStartAnimation;
function init() {
canvas = document.getElementById("canvas");
anim_container = document.getElementById("animation_container");
dom_overlay_container = document.getElementById("dom_overlay_container");
var comp=AdobeAn.getComposition("C1F9C7BD5BEEC941A1FE079EA94C1BF3");
var lib=comp.getLibrary();
handleComplete({},comp);
}
function handleComplete(evt,comp) {
//This function is always called, irrespective of the content. You can use the variable "stage" after it is created in token create_stage.
var lib=comp.getLibrary();
var ss=comp.getSpriteSheet();
exportRoot = new lib.iconskyscrapers();
stage = new lib.Stage(canvas);
//Registers the "tick" event listener.
fnStartAnimation = function() {
stage.addChild(exportRoot);
createjs.Ticker.setFPS(lib.properties.fps);
createjs.Ticker.addEventListener("tick", stage)
stage.addEventListener("tick", handleTick)
function getProjectionMatrix(totalDepth) {
var focalLength = 528.25;
var projectionCenter = { x : lib.properties.width/2, y : lib.properties.height/2 };
var scale = (totalDepth + focalLength)/focalLength;
var scaleMat = new createjs.Matrix2D;
scaleMat.a = 1/scale;
scaleMat.d = 1/scale;
var projMat = new createjs.Matrix2D;
projMat.tx = -projectionCenter.x;
projMat.ty = -projectionCenter.y;
projMat = projMat.prependMatrix(scaleMat);
projMat.tx += projectionCenter.x;
projMat.ty += projectionCenter.y;
return projMat;
}
function handleTick(event) {
var focalLength = 528.25;
var cameraInstance = exportRoot.___camera___instance;
if(cameraInstance !== undefined && cameraInstance.pinToObject !== undefined)
{
cameraInstance.x = cameraInstance.pinToObject.x + cameraInstance.pinToObject.pinOffsetX;
cameraInstance.y = cameraInstance.pinToObject.y + cameraInstance.pinToObject.pinOffsetY;
if(cameraInstance.pinToObject.parent !== undefined && cameraInstance.pinToObject.parent.depth !== undefined)
cameraInstance.depth = cameraInstance.pinToObject.parent.depth + cameraInstance.pinToObject.pinOffsetZ;
}
for(child in exportRoot.children)
{
var layerObj = exportRoot.children[child];
if(layerObj == cameraInstance)
continue;
if(layerObj.currentFrame != layerObj.parent.currentFrame)
{
layerObj.gotoAndPlay(layerObj.parent.currentFrame);
}
var matToApply = new createjs.Matrix2D;
var cameraMat = new createjs.Matrix2D;
var totalDepth = layerObj.layerDepth ? layerObj.layerDepth : 0;
var cameraDepth = 0;
if(cameraInstance && !layerObj.isAttachedToCamera)
{
var stageCenter = { 'x' : lib.properties.width/2, 'y' : lib.properties.height/2 };
var mat = cameraInstance.getMatrix();
mat.tx -= stageCenter.x;
mat.ty -= stageCenter.y;
cameraMat = mat.invert();
cameraMat.prependTransform(stageCenter.x, stageCenter.y, 1, 1, 0, 0, 0, 0, 0);
cameraMat.appendTransform(-stageCenter.x, -stageCenter.y, 1, 1, 0, 0, 0, 0, 0);
if(cameraInstance.depth)
cameraDepth = cameraInstance.depth;
}
if(layerObj.depth)
{
totalDepth = layerObj.depth;
}
//Offset by camera depth
totalDepth -= cameraDepth;
if(totalDepth < -focalLength)
{
matToApply.a = 0;
matToApply.d = 0;
}
else
{
if(layerObj.layerDepth)
{
var sizeLockedMat = getProjectionMatrix(layerObj.layerDepth);
if(sizeLockedMat)
{
sizeLockedMat.invert();
matToApply.prependMatrix(sizeLockedMat);
}
}
matToApply.prependMatrix(cameraMat);
var projMat = getProjectionMatrix(totalDepth);
if(projMat)
{
matToApply.prependMatrix(projMat);
}
}
layerObj.transformMatrix = matToApply;
}
}
}
//Code to support hidpi screens and responsive scaling.
function makeResponsive(isResp, respDim, isScale, scaleType) {
var lastW, lastH, lastS=1;
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
function resizeCanvas() {
var w = lib.properties.width, h = lib.properties.height;
var iw = window.innerWidth, ih=window.innerHeight;
var pRatio = window.devicePixelRatio || 1, xRatio=iw/w, yRatio=ih/h, sRatio=1;
if(isResp) {
if((respDim=='width'&&lastW==iw) || (respDim=='height'&&lastH==ih)) {
sRatio = lastS;
}
else if(!isScale) {
if(iw<w || ih<h)
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==1) {
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==2) {
sRatio = Math.max(xRatio, yRatio);
}
}
canvas.width = w*pRatio*sRatio;
canvas.height = h*pRatio*sRatio;
canvas.style.width = dom_overlay_container.style.width = anim_container.style.width = w*sRatio+'px';
canvas.style.height = anim_container.style.height = dom_overlay_container.style.height = h*sRatio+'px';
stage.scaleX = pRatio*sRatio;
stage.scaleY = pRatio*sRatio;
lastW = iw; lastH = ih; lastS = sRatio;
stage.tickOnUpdate = false;
stage.update();
stage.tickOnUpdate = true;
}
}
makeResponsive(false,'both',false,1);
AdobeAn.compositionLoaded(lib.properties.id);
fnStartAnimation();
}
</script>
HTML
<body onload="init();" style="margin:0px;">
<div id="animation_container" style="background-color:rgba(255, 255, 255, 1.00); width:113px; height:84px">
<canvas id="canvas" width="113" height="84" style="position: absolute; display: block; background-color:rgba(255, 255, 255, 1.00);"></canvas>
<div id="dom_overlay_container" style="pointer-events:none; overflow:hidden; width:113px; height:84px; position: absolute; left: 0px; top: 0px; display: block;">
</div>
</div>
</body>

Hover and onclick functionality issue in jquery

I want to have onclick and hover functionality simultaneously but if you have clicked somewhere then hover should not work until I click somewhere else. I have tried alot but I didn't find any working code. Kindly help
canvas.addEventListener('mousedown', function(evt) {
}, false);
canvas.onmousemove = function(evt) {
};
Well, I am not quite sure what you need and why you need it. But, in that short piece of code you wrote I saw the word "canvas" and thought "what the heck, that could be fun!". I have not much experience with the canvas element since earlier, so I realize there may be better ways of writing this code.
But, I hope what I wrote in the below example is at least close to what you were looking for. Otherwise, go nuts and change and adapt the way you like... and while you do that, try to learn something of it.
var Canvas = function() {
this.$canvas = $('canvas');
this.$currPos = $('#currPos');
this.$currClick = $('#currClick');
this.$clickInfo = $('#clickInfo');
this.canvsWidth = 150;
this.cavasHeight = 150;
this.ctx = ctx = this.$canvas[0].getContext('2d');
this.rect = this.$canvas[0].getBoundingClientRect();
this.squares = [];
this.sqm = 50;
this.tracker = 0;
this.latestHover = {};
this._events();
this._prepare();
};
Canvas.prototype._events = function() {
var self = this;
this.$canvas.on('mousemove', function(e) {
var posX = e.clientX - self.rect.left,
posY = e.clientY - self.rect.top,
newX = Math.floor(posX / self.sqm),
newY = Math.floor(posY / self.sqm);
if($.isEmptyObject(self.latestHover) || (self.latestHover.x !== newX || self.latestHover.y !== newY)) {
self.latestHover.x = newX;
self.latestHover.y = newY;
self.squares.map(function(k, v) {
let obj = self.squares[v];
if(!obj.fixedBackground) obj.reverseBackgroundColor();
});
var square = self.findObject(newX, newY)[0];
if(square) {
square.setBackgroundColor('#ff0000');
self.$currPos.html(newX +'x'+ newY);
self._redraw();
}
}
});
this.$canvas.on('click', function() {
if(self.tracker === 2) {
return self._reset();
}
if(!($.isEmptyObject(self.latestHover))) {
var x = self.latestHover.x,
y = self.latestHover.y;
var square = self.findObject(x, y)[0];
square.setFixedBackground();
self.$currClick.html(x +'x'+ y);
self.setTracker();
}
});
};
Canvas.prototype._prepare = function() {
for(var row = 0; row < 3; row++) {
for(var col = 0; col < 3; col++) {
this.squares.push(new Square(row, col, this.ctx, this.sqm));
}
}
};
Canvas.prototype._redraw = function() {
var self = this;
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
this.squares.filter(function(k, v) {
self.squares[v].draw();
});
};
Canvas.prototype.setTracker = function() {
this.tracker++;
if(this.tracker === 2) this.$clickInfo.html('Click one more time to start over');
};
Canvas.prototype.findObject = function(x, y) {
var self = this;
return square = self.squares.filter(function(k, v) {
var obj = self.squares[v];
if(obj.posX === x && obj.posY === y) return obj;
});
};
Canvas.prototype._reset = function() {
var self = this;
this.squares.map(function(k, v) {
let obj = self.squares[v];
obj.reverseBackgroundColor();
obj.unsetFixedBackground();
});
this.$currClick.html('');
this.$clickInfo.html('');
this.tracker = 0;
this._redraw();
};
var Square = function(x, y, ctx, sqm) {
this.ctx = ctx;
this.sqm = sqm;
this.posX = x;
this.posY = y;
this.background = '#fff';
this.strokeThickness = 1;
this.fixedBackground = false;
this.draw();
};
Square.prototype.setBackgroundColor = function(color) {
return this.background = color;
};
Square.prototype.reverseBackgroundColor = function() {
return this.background = '#fff';
};
Square.prototype.setFixedBackground = function() {
return this.fixedBackground = true;
};
Square.prototype.unsetFixedBackground = function() {
return this.fixedBackground = false;
};
Square.prototype.draw = function() {
this.ctx.fillStyle = this.background;
this.ctx.fillRect(this.posX * this.sqm, this.posY * this.sqm, this.sqm, this.sqm);
this.ctx.strokeRect(this.posX * this.sqm, this.posY * this.sqm, this.sqm, this.sqm);
};
window.Canvas = new Canvas();
canvas {
border: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas width="150" height="150"></canvas>
<div>
Current position: <span id="currPos"></span> <br/>
Last click: <span id="currClick"></span> <span id="clickInfo"></span>
</div>

Dragging a div should resize the other two divs

I have three div's left,right and seperator and on dragging div seperator should resize the left and right div's .
The html code is as follows
<div id="left">Left</div>
<div id="seperator"> </div>
<div id="right"> Right</div>
The seperator div is made draggable using following javascript
var dragObject = null;
var mouseOffset = null;
// document.onmousemove = mouseMove;
//document.onmouseup = mouseUp;
var div_id = document.getElementById('seperator');
makeDraggable(div_id);
function getMouseOffset(target, ev){
ev = ev || window.event;
var docPos = getPosition(target);
var mousePos = mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}
function getPosition(e){
var left = 0;
var top = 0;
while (e.offsetParent){
left += e.offsetLeft;
top += e.offsetTop;
e = e.offsetParent;
}
left += e.offsetLeft;
top += e.offsetTop;
return {x:left, y:top};
}
function mouseMove(ev){
ev = ev || window.event;
// var mousePos = mouseCoords(ev);
// mouseOffset = getMouseOffset(this, ev);
if(dragObject){
var div_left = document.getElementById('left');
var div_right = document.getElementById('right');
dragObject.style.position = 'relative';
div_left.style.position = 'relative';
div_left.style.width = ( (div_left.offsetWidth) -( mouseOffset.x) )+"px";
div_right.style.position = 'relative';
div_right.style.width = ((div_right.offsetWidth) + (mouseOffset.x)) + "px";
return false;
}
}
function mouseUp(){
dragObject = null;
}
function makeDraggable(item){
if(!item) return;
item.onmousedown = function(ev){
dragObject = this;
mouseOffset = getMouseOffset(this, ev);
var div_id = document.getElementById('seperator');
div_id.addEventListener('mousemove', mouseMove,true);
div_id.addEventListener('mouseup', mouseUp,true);
return false;
}
}
function mouseCoords(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
The code for resizing is done in the function mouseMove()
The code is explained as it on the following link
the link explains the dragging of div
so,I want to resize the left and right div's using div seperator

Categories