I have an SVG map and simple plugin which adds zoom and drag functionalities.
<svg>
<g class="main-container draggable" transform="matrix(1 0 0 1 0 0)">
<path id="AT-1" title="Burgenland" class="land" d=".../>
</g>
</svg>
const maxScale = 5,
minScale = 0.15;
var selected,
scale = 1,
svg = document.querySelector('svg');
function beginDrag(e) {
e.stopPropagation();
let target = e.target;
if (target.classList.contains('draggable')) {
selected = target;
} else {
selected = document.querySelector('.main-container');
}
selected.dataset.startMouseX = e.clientX;
selected.dataset.startMouseY = e.clientY;
}
function drag(e) {
if (!selected) return;
e.stopPropagation();
let startX = parseFloat(selected.dataset.startMouseX),
startY = parseFloat(selected.dataset.startMouseY),
dx = (e.clientX - startX),
dy = (e.clientY - startY);
if (selected.classList.contains('draggable')) {
let selectedBox = selected.getBoundingClientRect(),
boundaryBox = selected.parentElement.getBoundingClientRect();
if (selectedBox.right + dx > boundaryBox.right) {
dx = (boundaryBox.right - selectedBox.right);
} else if (selectedBox.left + dx < boundaryBox.left) {
dx = (boundaryBox.left - selectedBox.left);
}
if (selectedBox.bottom + dy > boundaryBox.bottom) {
dy = (boundaryBox.bottom - selectedBox.bottom);
}
else if (selectedBox.top + dy < boundaryBox.top) {
dy = (boundaryBox.top - selectedBox.top);
}
}
let currentMatrix = selected.transform.baseVal.consolidate().matrix,
newMatrix = currentMatrix.translate(dx / scale, dy / scale),
transform = svg.createSVGTransformFromMatrix(newMatrix);
selected.transform.baseVal.initialize(transform);
selected.dataset.startMouseX = dx + startX;
selected.dataset.startMouseY = dy + startY;
}
function endDrag(e) {
e.stopPropagation();
if (selected) {
selected = undefined;
}
}
function zoom(e) {
e.stopPropagation();
e.preventDefault();
let delta = e.wheelDelta,
container = document.querySelector('svg .main-container'),
scaleStep = delta > 0 ? 1.25 : 0.8;
if (scale * scaleStep > maxScale) {
scaleStep = maxScale / scale;
}
if (scale * scaleStep < minScale) {
scaleStep = minScale / scale;
}
scale *= scaleStep;
let box = svg.getBoundingClientRect();
let point = svg.createSVGPoint();
point.x = e.clientX - box.left;
point.y = e.clientY - box.top;
let currentZoomMatrix = container.getCTM();
point = point.matrixTransform(currentZoomMatrix.inverse());
let matrix = svg.createSVGMatrix()
.translate(point.x, point.y)
.scale(scaleStep)
.translate(-point.x, -point.y);
let newZoomMatrix = currentZoomMatrix.multiply(matrix);
container.transform.baseVal.initialize(svg.createSVGTransformFromMatrix(newZoomMatrix));
console.log("scale", scale);
let t = newZoomMatrix;
console.log("zoomMatrix", t.a, t.b, t.c, t.d, t.e, t.f);
}
document.querySelector('svg').addEventListener('mousedown', beginDrag);
document.querySelector('svg').addEventListener('mousewheel', zoom);
svg.addEventListener('mousemove', drag);
window.addEventListener('mouseup', endDrag);
At first sight, it works fine, however, it behaves strangely in some situations.
For example - if you zoom out I can freely drag it to any directions without any problem.
But if I zoom in to the scale that part of the map exceeds the parent element, any attempt to move it causes a jump of the entire map and blocks this functionality.
The second thing is - right now I can only move the map in the borders of SVG element and I want to have a possibility to drag it out outside it in the same way it works here: https://www.amcharts.com/svg-maps/?map=austria
Here is a snippet with my code: https://jsfiddle.net/marektchas/qo1eynag/3/
Posting here easy way for pan zoom functionality.
var svgCanvas = document.getElementById("canvas");
var viewPort = document.getElementById("viewport");
var drag = false;
var offset = { x: 0, y: 0 };
var factor = .1;
var matrix = new DOMMatrix();
svgCanvas.addEventListener('pointerdown', function (event) {
drag = true;
offset = { x: event.offsetX, y: event.offsetY };
});
svgCanvas.addEventListener('pointermove', function (event) {
if (drag) {
var tx = event.offsetX - offset.x;
var ty = event.offsetY - offset.y;
offset = {
x: event.offsetX,
y: event.offsetY
};
matrix.preMultiplySelf(new DOMMatrix()
.translateSelf(tx, ty));
viewPort.style.transform = matrix.toString();
}
});
svgCanvas.addEventListener('pointerup', function (event) {
drag = false;
});
svgCanvas.addEventListener('wheel', function (event) {
var zoom = event.deltaY > 0 ? -1 : 1;
var scale = 1 + factor * zoom;
offset = {
x: event.offsetX,
y: event.offsetY
};
matrix.preMultiplySelf(new DOMMatrix()
.translateSelf(offset.x, offset.y)
.scaleSelf(scale, scale)
.translateSelf(-offset.x, -offset.y));
viewPort.style.transform = matrix.toString();
});
html,
body {
height: 100%;
margin: 0;
box-sizing: border-box;
font-size: 62.5%;
}
body{
display: flex;
}
#around{
display: flex;
width: 100%;
border: 1px dashed orange;
}
#canvas{
flex: 1;
height: auto;
}
<div id="around">
<svg id="canvas" style="border: 1px solid blue;">
<g id="viewport">
<rect x="100" y="100" width="200" height="200" fill="red"/>
</g>
</svg>
</div>
It seems I found the solution however, I'm not quite sure how does it exactly work.
It works as expected if I remove .draggable class from the g element
Related
Here below is how to draw a "selection rectangle" on a <canvas> with drag-and-drop, see How to draw a selection rectangle with drag and drop on a HTML canvas?.
Is there a simple way to detect the selection rectangle on hover at a distance of a few pixels, and allow to move the selection rectangle with drag-and-drop?
var c1 = document.getElementById("c1"), c2 = document.getElementById("c2");
var ctx1 = c1.getContext("2d"), ctx2 = c2.getContext("2d");
ctx2.setLineDash([5, 5]);
var origin = null;
window.onload = () => { ctx1.drawImage(document.getElementById("img"), 0, 0); }
c2.onmousedown = e => { origin = {x: e.offsetX, y: e.offsetY}; };
window.onmouseup = e => { origin = null; };
c2.onmousemove = e => {
if (!!origin) {
ctx2.strokeStyle = "#ff0000";
ctx2.clearRect(0, 0, c2.width, c2.height);
ctx2.beginPath();
ctx2.rect(origin.x, origin.y, e.offsetX - origin.x, e.offsetY - origin.y);
ctx2.stroke();
}
};
#img { display: none; }
#canvas-container { position: relative; }
canvas { position: absolute; left: 0; top: 0; }
#c1 { z-index: 0; }
#c2 { z-index: 1; }
<img id="img" src="https://i.imgur.com/okSIKkW.jpg">
<div id="canvas-container">
<canvas id="c1" height="200" width="200"></canvas>
<canvas id="c2" height="200" width="200"></canvas>
</div>
Storing the current selection
To be able to move an existing selection, you have to save its state. Right now, your code "forgets" about it after drawing it once.
You can save your selection in a variable on mouseup like so:
const dx = origin.x - mouse.x;
const dy = origin.y - mouse.y;
selection = {
left: Math.min(mouse.x, origin.x),
top: Math.min(mouse.y, origin.y),
width: Math.abs(dx),
height: Math.abs(dy)
}
Intersection check
Your selection is a rectangle. You can check whether the mouse is intersecting the rectangle like so:
const intersects = (
mouse.x >= selection.left &&
mouse.x <= selection.left + selection.width &&
mouse.y >= selection.top &&
mouse.y <= selection.top + selection.height
);
If you want to add some padding around the rectangle, you can change the checks to be, for example, mouse.x >= selection.left - PADDING.
Make or Move
You now have to support 2 types of interactions:
Making new selections, and
Moving existing selections
This is where my implementation gets a bit messy, but you can probably refactor it yourself 🙂
I didn't change much in the making-selections code, other than saving the selection to a variable.
When moving selections, you take the dx and dy of your mouse drag and add them to the selection's original position (ox, oy):
const dx = origin.x - mouse.x;
const dy = origin.y - mouse.y;
selection.left = ox - dx;
selection.top = oy - dy;
Here's everything in a runnable snippet:
var c1 = document.getElementById("c1"),
c2 = document.getElementById("c2");
var ctx1 = c1.getContext("2d"),
ctx2 = c2.getContext("2d");
ctx2.setLineDash([5, 5]);
var origin = null;
let selection = null;
let selectionHovered = false;
let interaction = null;
let ox = null;
let oy = null;
window.onload = () => { ctx1.drawImage(document.getElementById("img"), 0, 0); }
c2.onmousedown = e => {
origin = {x: e.offsetX, y: e.offsetY};
if (selectionHovered) {
interaction = "MOVE_SELECTION";
ox = selection.left;
oy = selection.top;
} else {
interaction = "MAKE_SELECTION";
}
};
window.onmouseup = e => {
interaction = null;
origin = null;
};
c2.onmousemove = e => {
const x = e.offsetX;
const y = e.offsetY;
if (!interaction) {
selectionHovered = (
selection &&
x >= selection.left &&
x <= selection.left + selection.width &&
y >= selection.top &&
y <= selection.top + selection.height
);
} else {
const dx = origin.x - x;
const dy = origin.y - y;
// Update
switch (interaction) {
case "MOVE_SELECTION":
selection.left = ox - dx;
selection.top = oy - dy;
break;
case "MAKE_SELECTION":
selection = {
left: Math.min(x, origin.x),
top: Math.min(y, origin.y),
width: Math.abs(dx),
height: Math.abs(dy)
}
break
default:
// Do nothing
}
// Set selectionHovered
if (selection) {
} else {
selectionHovered = false;
}
}
// Draw
if (selection) drawSelection(selection);
};
function drawSelection({ top, left, width, height }) {
// Draw rect
ctx2.strokeStyle = "#ff0000";
ctx2.clearRect(0, 0, c2.width, c2.height);
ctx2.beginPath();
ctx2.rect(left, top, width, height);
ctx2.stroke();
// Set mouse
c2.style.cursor = selectionHovered ? "move" : "default";
}
#img { display: none; }
body { margin: 0; }
#canvas-container { position: relative; }
canvas { position: absolute; left: 0; top: 0; }
#c1 { z-index: 0; }
#c2 { z-index: 1; }
<img id="img" src="https://i.imgur.com/okSIKkW.jpg">
<div id="canvas-container">
<canvas id="c1" height="200" width="200"></canvas>
<canvas id="c2" height="200" width="200"></canvas>
</div>
When you drag the blue div, I'd like it to 'snap' into the middle of the green highlighted square when the mouse button is released. I cannot seem to find a way to read the coordinates from the box[] (Path2D()) interface. So is there a simple way to achieve this? Should I save the coordinates of the squares individually? Or can I somehow still get the points out of the Path2D interface?
const board = document.getElementById("board");
const ctxB = board.getContext("2d");
var Grid = false;
const boxsize = 64;
const amountOfrows = 8;
const amountOfHorBoxes = 7;
const totalAmountOfBoxes = amountOfrows * amountOfHorBoxes;
board.width = boxsize * 7.5;
board.height = boxsize * 8;
var addHorBox = 0;
var addVertBox = 0;
let boxes = [];
function drawGrid(){
Grid=true;
// for the amout of rows
for (let rowcount = 0; rowcount < amountOfrows; rowcount++) {
ctxB.lineWidth = 1;
ctxB.strokeStyle = "black";
ctxB.fillStyle = "white";
// filling the rows
if(rowcount%2==0){
for (let boxcount = 0; boxcount < amountOfHorBoxes; boxcount++) {
let box = new Path2D();
box.rect(addHorBox, addVertBox, boxsize, boxsize);
boxes.push(box);
ctxB.fill(box);
ctxB.stroke(box);
addHorBox+=boxsize;
}
}
addHorBox=0;
addVertBox+=boxsize;
}
}
MoveUnit(document.getElementById("unit"));
function MoveUnit(unit){
const rect = board.getBoundingClientRect();
const checkX = unit.clientWidth/2 - rect.left;
const checkY = unit.clientHeight/2 - rect.top;
var initialX;
var initialY;
var tile;
unit.onmousedown = mouseDown;
function mouseDown(e){
e = e || window.event;
e.preventDefault();
initialX = e.clientX;
initialY = e.clientY;
document.onmouseup = mouseUp;
document.onmousemove = moveMouse;
}
function moveMouse(e){
e = e || window.event;
e.preventDefault();
unit.style.top = (unit.offsetTop + e.clientY - initialY) + "px";
unit.style.left = (unit.offsetLeft + e.clientX - initialX) + "px";
boxes.forEach(box => {
if (ctxB.isPointInPath(box, unit.offsetLeft + checkX, unit.offsetTop + checkY)) {
ctxB.lineWidth = 2;
ctxB.fillStyle = 'green';
ctxB.fill(box);
ctxB.stroke(box);
tile=box;
}else{
ctxB.lineWidth = 1;
ctxB.strokeStyle = "black";
ctxB.fillStyle = 'white';
ctxB.fill(box);
ctxB.stroke(box);
}
});
// saving new mousepos after moving the unit
initialX = e.clientX;
initialY = e.clientY;
}
function mouseUp(){
document.onmousemove = false;
}
}
function loop(timestamp){
// draw once
if(Grid==false) drawGrid();
requestAnimationFrame(loop);
}
loop();
#board{
background-color: #999;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#unit{
background-color: rgb(134, 162, 224);
position: absolute;
cursor: pointer;
z-index: 1;
width: 30px;
height: 30px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="testing.css"/>
<title>Gridding</title>
</head>
<body>
<div id="unit"></div>
<canvas id="board"></canvas></div>
<script src="testing.js"></script>
</body>
</html>
In those Path2D instances we can add some useful data that can do what you need:
let box = new Path2D();
box.rect(...
box.data = { row, column }
then on the function mouseUp we use that to 'snap' into the middle
unit.style.top = ((box.data.column + 0.5) * boxsize) + "px";
unit.style.left = ((box.data.row + 0.5) * boxsize) + "px";
I reduced a lot of your code on my example below, I'm focusing just on the question, you should do the same when asking questions, that helps others get to the point faster and gives you a better chance of a quick answer.
const board = document.getElementById("board");
const ctxB = board.getContext("2d");
const unit = document.getElementById("unit");
const boxsize = 32;
board.width = board.height = boxsize * 4;
let boxes = [];
for (let r = 0; r < 4; r++) {
for (let c = 0; c < 4; c++) {
let box = new Path2D();
box.rect(r * boxsize, c * boxsize, boxsize -0.5, boxsize -0.5);
box.data = { r, c }
boxes.push(box);
}
}
var position = { x: -1, y: -1 }
function mouseDown(e) {
document.onmouseup = mouseUp;
document.onmousemove = moveMouse;
position = { x: e.clientX, y: e.clientY}
}
function mouseUp() {
document.onmousemove = false;
boxes.forEach(box => {
if (ctxB.isPointInPath(box, position.x, position.y)) {
unit.style.top = ((box.data.c + 0.5) * boxsize) + "px";
unit.style.left = ((box.data.r + 0.5) * boxsize) + "px";
}
});
}
function moveMouse(e) {
unit.style.top = (unit.offsetTop + e.clientY - position.y) + "px";
unit.style.left = (unit.offsetLeft + e.clientX - position.x) + "px";
position = { x: e.clientX, y: e.clientY}
}
function loop(timestamp) {
ctxB.clearRect(0, 0, board.width, board.height)
boxes.forEach(box => {
ctxB.fillStyle = ctxB.isPointInPath(box, position.x, position.y)? 'green' : 'white'
ctxB.fill(box);
ctxB.stroke(box);
});
requestAnimationFrame(loop);
}
loop();
unit.onmousedown = mouseDown;
#unit {
background-color: blue;
position: absolute;
width: 20px;
height: 20px;
}
<canvas id="board"></canvas>
<br>
<div id="unit"></div>
In my code I'm separating the mouse events from the drawing,
we draw only on the loop.
the events change state variables.
Also noticed that in some cases two boxes got highlighted at the same time changing the size of the rect by a tiny bit fixed that boxsize -0.5
My web project needs to zoom a div element around the mouse position as anchor while mouse wheeling, I was inspired by #Tatarize 's answer at Zoom in on a point (using scale and translate), but I can't implement it exactly, it can't zoom and translate around the mouse position, can any one help?
window.onload = function() {
const STEP = 0.05;
const MAX_SCALE = 10;
const MIN_SCALE = 0.01;
const red = document.getElementById('red');
const yellow = red.parentNode;
let scale = 1;
yellow.onmousewheel = function (event) {
event.preventDefault();
let mouseX = event.clientX - yellow.offsetLeft - red.offsetLeft;
let mouseY = event.clientY - yellow.offsetTop - red.offsetTop;
const factor = event.wheelDelta / 120;
const oldScale = scale;
scale = scale + STEP * factor;
scale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale));
const scaleChanged = scale - oldScale;
const offsetX = -(mouseX * scaleChanged);
const offsetY = -(mouseY * scaleChanged);
console.log(offsetX, offsetY);
red.style.transform = 'translate(' + offsetX + 'px, ' + offsetY + 'px)' + 'scale(' + scale + ')';
}
}
.yellow {
background-color: yellow;
width: 400px;
height: 200px;
}
.red {
background-color: red;
width: 100px;
height: 50px;
}
<div class="yellow">
<div id="red" class="red"></div>
</div>
Really incredible, I actually did it.
window.onload = () => {
const STEP = 0.99;
const MAX_SCALE = 5;
const MIN_SCALE = 0.01;
const red = document.getElementById("red");
const yellow = red.parentNode;
let scale = 1;
const rect = red.getBoundingClientRect();
const originCenterX = rect.x + rect.width / 2;
const originCenterY = rect.y + rect.height / 2;
yellow.onwheel = (event) => {
event.preventDefault();
const factor = event.deltaY;
// If current scale is equal to or greater than MAX_SCALE, but you're still zoom in it, then return;
// If current scale is equal to or smaller than MIN_SCALE, but you're still zoom out it, then return;
// Can not use Math.max and Math.min here, think about it.
if ((scale >= MAX_SCALE && factor < 0) || (scale <= MIN_SCALE && factor > 0)) return;
const scaleChanged = Math.pow(STEP, factor);
scale *= scaleChanged;
const rect = red.getBoundingClientRect();
const currentCenterX = rect.x + rect.width / 2;
const currentCenterY = rect.y + rect.height / 2;
const mousePosToCurrentCenterDistanceX = event.clientX - currentCenterX;
const mousePosToCurrentCenterDistanceY = event.clientY - currentCenterY;
const newCenterX = currentCenterX + mousePosToCurrentCenterDistanceX * (1 - scaleChanged);
const newCenterY = currentCenterY + mousePosToCurrentCenterDistanceY * (1 - scaleChanged);
// All we are doing above is: getting the target center, then calculate the offset from origin center.
const offsetX = newCenterX - originCenterX;
const offsetY = newCenterY - originCenterY;
// !!! Both translate and scale are relative to the original position and scale, not to the current.
red.style.transform = 'translate(' + offsetX + 'px, ' + offsetY + 'px)' + 'scale(' + scale + ')';
}
}
.yellow {
background-color: yellow;
width: 200px;
height: 100px;
margin-left: 50px;
margin-top: 50px;
position: absolute;
}
.red {
background-color: red;
width: 200px;
height: 100px;
position: absolute;
}
<div class="yellow">
<div id="red" class="red"></div>
</div>
.onmousewheel is deprecated. Use .onwheel instead.
Also, onwheel event doesn't have wheelDelta property. Use deltaY.
My code given there is to change the viewbox with regard to a zoom point. You are moving the rectangle based on some math that doesn't fit that situation.
The idea is to pan the zoom box with regard to the change in the scale. You are changing the position and location of a rectangle. Which is to say you need to simulate the new position of the red rectangle as if the yellow rectangle were a viewport. Which means that when we zoom in, we are zooming in at a translateX translateY position of a particular scale factor. We then need to translate the value of the zoom point into the right scene space. Then adjust the position of the red rectangle as if it were in that scene space.
Here's the code with some corrections, though I'm clearly missing a few elements. The big thing is the lack of preservation of the translateX translateY stuff. You overwrite it so it ends up just preserving the zoom and screwing up the translateX, translateY stuff back to zero when it's a relative offset of the viewport.
In functional code, zooming in in the rectangle will make the red rectangle fill the entire scene space.
window.onload = function() {
const STEP = 0.05;
const MAX_SCALE = 10;
const MIN_SCALE = 0.01;
const red = document.getElementById('red');
const yellow = document.getElementById('yellow');
const svgArea = document.getElementById('svgArea');
let viewportTranslateX = 0;
let viewportTranslateY = 0;
let viewportScale = 1;
svgArea.onwheel = function (event) {
event.preventDefault();
console.log("mouse coords", event.clientX, event.clientY);
let zoompointX = (event.clientX + (viewportTranslateX / viewportScale)) * viewportScale;
let zoompointY = (event.clientY + (viewportTranslateY / viewportScale)) * viewportScale;
console.log("zoom point prezoom", zoompointX, zoompointY);
const factor = event.deltaY / 120;
const oldScale = viewportScale;
viewportScale = viewportScale * (1 + STEP * factor);
viewportScale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, viewportScale));
const scaleChanged = viewportScale - oldScale;
const offsetX = -(zoompointX * scaleChanged);
const offsetY = -(zoompointY * scaleChanged);
console.log("scale", scaleChanged, offsetX, offsetY);
viewportTranslateX += offsetX;
viewportTranslateY += offsetY;
zoompointX = (event.clientX + (viewportTranslateX / viewportScale)) * viewportScale;
zoompointY = (event.clientY + (viewportTranslateY / viewportScale)) * viewportScale;
console.log("zoompoint postzoom", zoompointX, zoompointY);
var x = viewportTranslateX;
var y = viewportTranslateY;
var width = (svgArea.getAttribute("width") * viewportScale);
var height = (svgArea.getAttribute("height") * viewportScale);
svgArea.setAttribute("viewBox", x + " " + y + " " + width + " " + height);
console.log("viewport", x, y, width, height, viewportScale);
}
}
<svg id="svgArea" width=400 height=200 viewBox="0,0,400,200">
<rect id="yellow" width=400 height=200 fill="yellow"/>
<rect id="red" width=100 height=50 fill="red"/>
</svg>
The goal is simple, using a mousewheel, zoom into a specific point (where the mouse is). This means after zooming the mouse will be in the same roughly the same spot of the picture.
(Purely illustrative, I don't care if you use dolphins, ducks or madonna for the image)
I do not wish to use canvas, and so far I've tried something like this:
HTML
<img src="whatever">
JS
function zoom(e){
var deltaScale = deltaScale || -e.deltaY / 1000;
var newScale = scale + deltaScale;
var newWidth = img.naturalWidth * newScale;
var newHeight = img.naturalHeight * newScale;
var x = e.pageX;
var y = e.pageY;
var newX = x * newWidth / img.width;
var newY = y * newHeight / img.height;
var deltaX = newX - x;
var deltaY = newY - y;
setScale(newScale);
setPosDelta(-deltaX,-deltaY);
}
function setPosDelta(dX, dY) {
var imgPos = getPosition();
setPosition(imgPos.x + dX, imgPos.y + dY);
}
function getPosition() {
var x = parseFloat(img.style.left);
var y = parseFloat(img.style.top);
return {
x: x,
y: y
}
}
function setScale(n) {
scale = n;
img.width = img.naturalWidth * n;
img.height = img.naturalHeight * n;
}
What this attempts to do is calculate the x,y coordinates of the dolphin's eye before and after the zoom, and after calculating the distance between those two points, substracts it from the left,top position in order to correct the zoom displacement, with no particular success.
The zoom occurs naturally extending the image to the right and to the bottom, so the correction tries to pull back to the left and to the top in order to keep the mouse on that damn dolphin eye! But it definitely doesn't.
Tell me, what's wrong with the code/math? I feel this question is not too broad, considering I couldn't find any solutions besides the canvas one.
Thanks!
[EDIT] IMPORTANT
CSS transform order matters, if you follow the selected answer, make sure you order the transition first, and then the scale. CSS transforms are executed backwards (right to left) so the scaling would be processed first, and then the translation.
Here is an implementation of zooming to a point. The code uses the CSS 2D transform and includes panning the image on a click and drag. This is easy because of no change in scale.
The trick when zooming is to normalize the offset amount using the current scale (in other words: divide it by the current scale) first, then apply the new scale to that normalized offset. This keeps the cursor exactly where it is independent of scale.
var scale = 1,
panning = false,
xoff = 0,
yoff = 0,
start = {x: 0, y: 0},
doc = document.getElementById("document");
function setTransform() {
doc.style.transform = "translate(" + xoff + "px, " + yoff + "px) scale(" + scale + ")";
}
doc.onmousedown = function(e) {
e.preventDefault();
start = {x: e.clientX - xoff, y: e.clientY - yoff};
panning = true;
}
doc.onmouseup = function(e) {
panning = false;
}
doc.onmousemove = function(e) {
e.preventDefault();
if (!panning) {
return;
}
xoff = (e.clientX - start.x);
yoff = (e.clientY - start.y);
setTransform();
}
doc.onwheel = function(e) {
e.preventDefault();
// take the scale into account with the offset
var xs = (e.clientX - xoff) / scale,
ys = (e.clientY - yoff) / scale,
delta = (e.wheelDelta ? e.wheelDelta : -e.deltaY);
// get scroll direction & set zoom level
(delta > 0) ? (scale *= 1.2) : (scale /= 1.2);
// reverse the offset amount with the new scale
xoff = e.clientX - xs * scale;
yoff = e.clientY - ys * scale;
setTransform();
}
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
#document {
width: 100%;
height: 100%;
transform-origin: 0px 0px;
transform: scale(1) translate(0px, 0px);
}
<div id="document">
<img style="width: 100%"
src="https://i.imgur.com/fHyEMsl.jpg"
crossOrigin="" />
</div>
This is an implementation that is closer to your original idea using top and left offsets and modifying the width attribute of the image instead of using the css transform in my other answer.
var scale = 1.0,
img = document.getElementById("image"),
deltaX = 0,
deltaY = 0;
// set the initial scale once the image is loaded
img.onload = function() {
scale = image.offsetWidth / image.naturalWidth;
}
img.onwheel = function(e) {
e.preventDefault();
// first, remove the scale so we have the native offset
var xoff = (e.clientX - deltaX) / scale,
yoff = (e.clientY - deltaY) / scale,
delta = (e.wheelDelta ? e.wheelDelta : -e.deltaY);
// get scroll direction & set zoom level
(delta > 0) ? (scale *= 1.05) : (scale /= 1.05);
// limit the smallest size so the image does not disappear
if (img.naturalWidth * scale < 16) {
scale = 16 / img.naturalWidth;
}
// apply the new scale to the native offset
deltaX = e.clientX - xoff * scale;
deltaY = e.clientY - yoff * scale;
// now modify the attributes of the image to reflect the changes
img.style.top = deltaY + "px";
img.style.left = deltaX + "px";
img.style.width = (img.naturalWidth * scale) + "px";
}
window.onresize = function(e) {
document.getElementById("wrapper").style.width = window.innerWidth + "px";
document.getElementById("wrapper").style.height = window.innerHeight + "px";
}
window.onload = function(e) {
document.getElementById("wrapper").style.width = window.innerWidth + "px";
document.getElementById("wrapper").style.height = window.innerHeight + "px";
}
html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
div {
overflow: hidden;
}
<div id="wrapper" style="position:relative;">
<img id="image" style="width:100%;position:absolute;top:0px;left:0px;"
src="https://i.imgur.com/fHyEMsl.jpg"
crossOrigin="" />
</div>
I liked the both posts from fmacdee. I factored the code he created out to be a reusable version that can be called on any image.
just call:
var imageScaler = new ImageScaler(document.getElementById("image"));
imageScaler.setup();
and include this code somewhere in your project:
var ImageScaler = function(img)
{
this.img = img;
this.scale = this.getImageScale();
this.panning = false;
this.start = {x: 0, y: 0};
this.delta = {x: 0, y: 0};
};
ImageScaler.prototype =
{
constructor: ImageScaler,
setup: function()
{
this.setupEvents();
},
setupEvents: function()
{
var img = this.img;
var callBack = this.onScale.bind(this);
var touchDown = this.touchDown.bind(this),
touhcMove = this.touchMove.bind(this),
touchUp = this.touchUp.bind(this);
img.onwheel = callBack;
img.onmousedown = touchDown;
img.onmousemove = touhcMove;
img.onmouseup = touchUp;
},
getImageScale: function()
{
var img = this.img;
return img.offsetWidth / img.naturalWidth;
},
getMouseDirection: function(e)
{
return (e.wheelDelta ? e.wheelDelta : -e.deltaY);
},
getOffset: function(e)
{
var scale = this.scale,
delta = this.delta;
// first, remove the scale so we have the native offset
return {
x: (e.clientX - delta.x) / scale,
y: (e.clientY - delta.y) / scale
};
},
scaleElement: function(x, y, scale)
{
var img = this.img;
img.style.top = y + "px";
img.style.left = x + "px";
img.style.width = (img.naturalWidth * scale) + "px";
},
minScale: 0.2,
updateScale: function(delta)
{
// get scroll direction & set zoom level
var scale = (delta > 0) ? (this.scale *= 1.05) : (this.scale /= 1.05);
// limit the smallest size so the image does not disappear
if (scale <= this.minScale)
{
this.scale = this.minScale;
}
return this.scale;
},
touchDown: function(e)
{
var delta = this.delta;
this.start = {x: e.clientX - delta.x, y: e.clientY - delta.y};
this.panning = true;
},
touchMove: function(e)
{
e.preventDefault();
if (this.panning === false)
{
return;
}
var delta = this.delta,
start = this.start;
delta.x = (e.clientX - start.x);
delta.y = (e.clientY - start.y);
console.log(delta, start)
this.scaleElement(delta.x, delta.y, this.scale);
},
touchUp: function(e)
{
this.panning = false;
},
onScale: function(e)
{
var offset = this.getOffset(e);
e.preventDefault();
// get scroll direction & set zoom level
var delta = this.getMouseDirection(e);
var scale = this.updateScale(delta);
// apply the new scale to the native offset
delta = this.delta;
delta.x = e.clientX - offset.x * scale;
delta.y = e.clientY - offset.y * scale;
this.scaleElement(delta.x, delta.y, scale);
}
};
I made a fiddle to view the results: http://jsfiddle.net/acqo5n8s/12/
I am using KonvaJs in my project. I need to implement drag bound to Konva.Layer. My layer has so many other shapes and images. I need to restrict the movement of layer up to 50% of it's width and height. The way I have done in this plunkr. The problem arises when user zoom-in or zoom-out the layer using mouse wheel. After the zoom, I don't know why the drag bound is behaving differently. Seems like I am not able to do the Math correctly. I need to have the same behavior i.e. the way movement of layer is restricted when user does not perform zoom. This is what I am doing:
//... a helper object for zooming
var zoomHelper = {
stage: null,
scale: 1,
zoomFactor: 1.1,
origin: {
x: 0,
y: 0
},
zoom: function(event) {
event.preventDefault();
var delta;
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
if (event.originalEvent.detail > 0) {
//scroll down
delta = 0.2;
} else {
//scroll up
delta = 0;
}
} else {
if (event.originalEvent.wheelDelta < 0) {
//scroll down
delta = 0.2;
} else {
//scroll up
delta = 0;
}
}
var evt = event.originalEvent,
mx = evt.clientX - zoomHelper.stage.getX(),
my = evt.clientY - zoomHelper.stage.getY(),
zoom = (zoomHelper.zoomFactor - delta),
newscale = zoomHelper.scale * zoom;
zoomHelper.origin.x = mx / zoomHelper.scale + zoomHelper.origin
.x - mx / newscale;
zoomHelper.origin.y = my / zoomHelper.scale + zoomHelper.origin
.y - my / newscale;
zoomHelper.stage.setOffset({
x: zoomHelper.origin.x,
y: zoomHelper.origin.y
});
zoomHelper.stage.setScale({
x: newscale,
y: newscale
});
zoomHelper.stage.draw();
zoomHelper.scale *= zoom;
preCalculation();
}
};
// Code goes here
var w = window.innerWidth;
var h = window.innerHeight;
var height, minX, minY, maxX, maxY;
var stage = new Konva.Stage({
container: 'container',
width: w,
height: h
});
zoomHelper.stage =stage;
var layer = new Konva.Layer({
draggable: true,
dragBoundFunc: function(pos) {
console.log('called');
var X = pos.x;
var Y = pos.y;
if (X < minX) {
X = minX;
}
if (X > maxX) {
X = maxX;
}
if (Y < minY) {
Y = minY;
}
if (Y > maxY) {
Y = maxY;
}
return ({
x: X,
y: Y
});
}
});
stage.add(layer);
function preCalculation(){
// pre-calc some bounds so dragBoundFunc has less calc's to do
height = layer.getHeight();
minX = stage.getX() - layer.getWidth() / 2;
maxX = stage.getX() + stage.getWidth() - layer.getWidth() / 2;
minY = stage.getY() - layer.getHeight() / 2;
maxY = stage.getY() + stage.getHeight() - layer.getHeight() / 2;
console.log(height, minX, minY, maxX, maxY);
}
preCalculation();
var img = new Image();
img.onload = function() {
var floorImage = new Konva.Image({
image: img,
width: w,
height: h
});
layer.add(floorImage);
layer.draw();
};
img.src = 'https://s.yimg.com/pw/images/coverphoto02_h.jpg.v3';
$(stage.container).on('mousewheel DOMMouseScroll', zoomHelper.zoom);
While using dragBoundFunc you have to return absolute position of layer. As you are changing attributes of top node (stage) it can be hard to maintain absolute position. So you can try to set bound function inside 'dragmove' event:
layer.on('dragmove', function() {
var x = Math.max(minX, Math.min(maxX, layer.x()));
var y = Math.max(minY, Math.min(maxY, layer.y()));
layer.x(x);
layer.y(y);
});
http://plnkr.co/edit/31MUmOjXBUVuaHVJsL3c?p=preview