I would like to achieve this effect outlined here: http://www.html5canvastutorials.com/labs/html5-canvas-multi-touch-scale-stage-with-kineticjs/
But on a Layer in KineticJS
I have already got it working to a degree (using basically the same code as in the link), but it seems the Layer scales around the 0,0 origin point and I cannot see any doco about changing the transform origin?
How can I effectively pinch and zoom a Layer such that it scales around it center point?
I made a plugin for this kind of behavior: https://github.com/eduplus/pinchlayer
It is probably a little outdated now with the recent changes, but the logic in layerTouchMove function is most likely still sound. Here:
var touch1 = event.touches[0];
var touch2 = event.touches[1];
if (touch1 && touch2) {
self.setDraggable(false);
if (self.trans != undefined) { self.trans.stop(); }
if (self.startDistance === undefined) {
self.startDistance = self.getDistance(touch1, touch2);
self.touchPosition.x = (touch1.clientX + touch2.clientX) / 2;
self.touchPosition.y = (touch1.clientY + touch2.clientY) / 2;
self.layerPosition.x = (Math.abs(self.getX()) + self.touchPosition.x) / self.startScale;
self.layerPosition.y = (Math.abs(self.getY()) + self.touchPosition.y) / self.startScale;
}
else {
var dist = self.getDistance(touch1, touch2);
var scale = (dist / self.startDistance) * self.startScale;
if (scale < self.minScale) { scale = self.minScale; }
if (scale > self.maxScale) { scale = self.maxScale; }
self.setScale(scale, scale);
var x = (self.layerPosition.x * scale) - self.touchPosition.x;
var y = (self.layerPosition.y * scale) - self.touchPosition.y;
var pos = self.checkBounds({ x: -x, y: -y });
self.setPosition(pos.x, pos.y);
self.draw();
}
Basically it will record the starting point and the distance (how long the pinch is) and then scale and set the layer position accordingly. Hope this helps.
Related
I'm trying to implement a zoom function using the mouse wheel in JointJS. The intent is to use the paper.scale() function and use the mouse coordinates for the ox & oy options. However, when I move the mouse it gets a jittery effect in the translation.
There are several zoom implementations available with a quick google search, but they all seem to suffer from the same issue.
Here is my code based on my best iterpretation of the JointJS documentation. I'm assuming the x & y are already translated to paperspace.
paper.on('blank:mousewheel', function(evt, x, y, delta) {
var normalizedDelta = Math.max(-1, Math.min(1, (delta))) / 50;
var newScale = paper.scale().sx + normalizedDelta; // the current paper scale changed by delta
if (newScale > 0.4 && newScale < 2) {
paper.translate(0, 0); // setOrigin is deprecated, replaced by translate
paper.scale(newScale, newScale, x, y);
}
})
Here is some zoom code I found by googling. It has the same effect. I've messed around with using offsetX/offsetY, local coordinates, & paper coordinates, all without luck.
paper.$el.on('mousewheel DOMMouseScroll', onMouseWheel);
function onMouseWheel(e) {
e.preventDefault();
e = e.originalEvent;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))) / 50;
var offsetX = (e.offsetX || e.clientX - $(this).offset().left); // offsetX is not defined in FF
var offsetY = (e.offsetY || e.clientY - $(this).offset().top); // offsetY is not defined in FF
var localPoint = offsetToLocalPoint(offsetX, offsetY);
var newScale = V(paper.viewport).scale().sx + delta; // the current paper scale changed by delta
if (newScale > 0.4 && newScale < 2) {
paper.translate(0, 0); // setOrigin is deprecated, replaced by translate
paper.scale(newScale, newScale, localPoint.x, localPoint.y); //p.x, p.y);
}
}
function offsetToLocalPoint(x, y) {
var svgPoint = paper.svg.createSVGPoint();
svgPoint.x = x;
svgPoint.y = y;
// Transform point into the viewport coordinate system.
var pointTransformed = svgPoint.matrixTransform(paper.viewport.getCTM().inverse());
return pointTransformed;
}
I'm expecting this to zoom in on whatever point the mouse is located. The scaling works quite nicely when the ox & oy are set to zero. When I attempt to use the mouse coordinates for the ox & oy options, it appears to work. However, when I move the mouse around it gets a jittery translation effect. It seems like the ox & oy coordinates are delayed by one event.
Here is my attempt JSFiddle.
Here is the attempt I found via google JSFiddle
I finally did it:
paper.on("blank:mousewheel", function(evt, x, y, delta) {
evt.preventDefault();
const oldscale = paper.scale().sx;
const newscale = oldscale + 0.2 * delta * oldscale
if (newscale>0.2 && newscale<5) {
paper.scale(newscale, newscale, 0, 0);
paper.translate(-x*newscale+evt.offsetX,-y*newscale+evt.offsetY);
}
});
https://jsfiddle.net/nj5cqusg/1/
I'm using the svg-pan-zoom code https://github.com/ariutta/svg-pan-zoom to make an svg map of some kind, now it is time to add a feature to pan & zoom to an art component of the svg on a click event. However, I'm not sure how to use the panBy() function to get to a desired svg art item: I tried to use the getBBox() on the group I'm looking to pan to and use that with the panZoomInstance.getPan() and getSizes() information, but my experiments are not working out.
I'd like to accomplish the same king of animation as their example (http://ariutta.github.io/svg-pan-zoom/demo/simple-animation.html) but center the viewport to the item.
Against all odds I was able to figure out this part of it!
function customPanByZoomAtEnd(amount, endZoomLevel, animationTime){ // {x: 1, y: 2}
if(typeof animationTime == "undefined"){
animationTime = 300; // ms
}
var animationStepTime = 15 // one frame per 30 ms
, animationSteps = animationTime / animationStepTime
, animationStep = 0
, intervalID = null
, stepX = amount.x / animationSteps
, stepY = amount.y / animationSteps;
intervalID = setInterval(function(){
if (animationStep++ < animationSteps) {
panZoomInstance.panBy({x: stepX, y: stepY})
} else {
// Cancel interval
if(typeof endZoomLevel != "undefined"){
var viewPort = $(".svg-pan-zoom_viewport")[0];
viewPort.style.transition = "all " + animationTime / 1000 + "s ease";
panZoomInstance.zoom(endZoomLevel);
setTimeout(function(){
viewPort.style.transition = "none";
$("svg")[0].style.pointerEvents = "all"; // re-enable the pointer events after auto-panning/zooming.
panZoomInstance.enablePan();
panZoomInstance.enableZoom();
panZoomInstance.enableControlIcons();
panZoomInstance.enableDblClickZoom();
panZoomInstance.enableMouseWheelZoom();
}, animationTime + 50);
}
clearInterval(intervalID)
}
}, animationStepTime)
}
function panToElem(targetElem) {
var initialSizes = panZoomInstance.getSizes();
var initialLoc = panZoomInstance.getPan();
var initialBounds = targetElem.getBoundingClientRect();
var initialZoom = panZoomInstance.getZoom();
var initialCX = initialBounds.x + (initialBounds.width / 2);
var initialCY = initialBounds.y + (initialBounds.height / 2);
var dX = (initialSizes.width / 2) - initialCX;
var dY = (initialSizes.height / 2) - initialCY;
customPanByZoomAtEnd({x: dX, y: dY}, 2, 700);
}
The key was in calculating the difference between the center of the viewport width & height from panZoomInstance.getSizes() and the center of the target element's client bounding rectangle.
Now the issue is trying to make an animated zoom. For now I've made it do a zoom to a specified location with a command at the end of the panning animation and set some css to make the zoom a smooth transition. The css gets removed after some time interval so normal zooming and panning isn't affected. In my attempts to make the zoom a step animation it always appeared to zoom past the intended max point.
I'm working on an orthographic camera for our THREE.js app. Essentially, this camera will present the scene to the user in 2D (users have the option of switching between the 2D and 3D camera). This camera will allow for panning and zooming to mouse point. I have the panning working, and I have zooming working, but not zooming to mouse point. Here's my code:
import React from 'react';
import T from 'three';
let panDamper = 0.15;
let OrthoCamera = React.createClass({
getInitialState: function () {
return {
distance: 150,
position: { x: 8 * 12, y: 2 * 12, z: 20 * 12 },
};
},
getThreeCameraObject: function () {
return this.camera;
},
applyPan: function (x, y) { // Apply pan by changing the position of the camera
let newPosition = {
x: this.state.position.x + x * -1 * panDamper,
y: this.state.position.y + y * panDamper,
z: this.state.position.z
};
this.setState({position: newPosition});
},
applyDirectedZoom: function(x, y, z) {
let zoomChange = 10;
if(z < 0) zoomChange *= -1;
let newDistance = this.state.distance + zoomChange;
let mouse3D = {
x: ( x / window.innerWidth ) * 2 - 1,
y: -( y / window.innerHeight ) * 2 + 1
};
let newPositionVector = new T.Vector3(mouse3D.x, mouse3D.y, 0.5);
newPositionVector.unproject(this.camera);
newPositionVector.sub(this.camera.position);
let newPosition = {
x: newPositionVector.x,
y: newPositionVector.y,
z: this.state.position.z
};
this.setState({
distance: newDistance,
position: newPosition
});
},
render: function () {
let position = new T.Vector3(this.state.position.x, this.state.position.y, this.state.position.z);
let left = (this.state.distance / -2) * this.props.aspect + this.state.position.x;
let right = (this.state.distance / 2) * this.props.aspect + this.state.position.x;
let top = (this.state.distance / 2) + this.state.position.y;
let bottom = (this.state.distance / -2) + this.state.position.y;
// Using react-three-renderer
// https://github.com/toxicFork/react-three-renderer
return <orthographicCamera
{...(_.pick(this.props, ['near', 'far', 'name']))}
position={position}
left={left}
right={right}
top={top}
bottom={bottom}
ref={(camera) => this.camera = camera}/>
}
});
module.exports = OrthoCamera;
Some zooming towards the mouse point happens but it seems erratic. I want to keep a 2D view, so as I zoom, I also move the camera (rather than having a non-perpendicular target, which kills the 2D effect).
I took cues from this question. As far as I can tell, I am successfully converting to THREE.js coordinates in mouse3D (see the answer to this question).
So, given this setup, how can I smoothly zoom to the mouse point (mouse3D) using the orthographic camera and maintaining a two dimensional view? Thanks in advance.
Assuming you have a camera that is described by a position and a look-at (or pivot) point in world coordinates, zooming at (or away from) a specific point is quite simple at its core.
Your representation seems to be even simpler: just a position/distance pair. I didn't see a rotation component, so I'll assume your camera is meant to be a top-down orthographic one.
In that case, your look-at point (which you won't need) is simply (position.x, position.y - distance, position.z).
In the general case, all you need to do is move both the camera position and the look-at point towards the zoom-at point while preserving the camera normal (i.e. direction). Note that this will work regardless of projection type or camera rotation. EDIT (2020/05/01): When using an orthographic projection, this is not all you need to do (see update at the bottom).
If you think about it, this is exactly what happens when you're zooming at a point in 3D. You keep looking at the same direction, but you move ever closer (without ever reaching) your target.
If you want to zoom by a factor of 1.1 for example, you can imagine scaling the vector connecting your camera position to your zoom-at point by 1/1.1.
You can do that by simply interpolating:
var newPosition = new THREE.Vector3();
newPosition.x = (orgPosition.x - zoomAt.x) / zoomFactor + zoomAt.x;
newPosition.y = (orgPosition.y - zoomAt.y) / zoomFactor + zoomAt.y;
newPosition.z = (orgPosition.z - zoomAt.z) / zoomFactor + zoomAt.z;
As I said above, in your case you won't really need to update a look-at point and then calculate the new distance. Your new distance will simply be:
var newDistance = newPosition.y
That should do it.
It only gets a little bit more sophisticated (mainly in the general case) if you want to set minimum and maximum distance limits both between the position/look-at and position/zoom-at point pairs.
UPDATE (2020/05/01):
I just realized that the above, although correct (except for missing one minor but very important step) is not a complete answer to OP's question. Changing the camera's position in orthographic mode won't of course change the scale of graphics being rendered. For that, the camera's projection matrix will have to be updated (i.e. the left, right, top and bottom parameters of the orthographic projection will have to be changed).
For this reason, many graphics libraries include a scaling factor in their orthographic camera class, which does exactly that. I don't have experience with ThreeJS, but I think that property is called 'zoom'.
So, summing everything up:
var newPosition = new THREE.Vector3();
newPosition.x = (orgPosition.x - zoomAt.x) / zoomFactor + zoomAt.x;
newPosition.y = (orgPosition.y - zoomAt.y) / zoomFactor + zoomAt.y;
newPosition.z = (orgPosition.z - zoomAt.z) / zoomFactor + zoomAt.z;
myCamera.zoom = myCamera.zoom * zoomFactor
myCamera.updateProjectionMatrix()
If you want to use your orthographic camera class code above instead, you will probably have to change the section that computes left, right, top and bottom and add a scaling factor in the calculation. Here's an example:
var aspect = this.viewportWidth / this.viewportHeight
var dX = (this.right - this.left)
var dY = (this.top - this.bottom) / aspect
var left = -dX / (2 * this.scale)
var right = dX / (2 * this.scale)
var bottom = -dY / (2 * this.scale)
var top = dY / (2 * this.scale)
mat4.ortho(this.mProjection, left, right, bottom, top, this.near, this.far)
I'm using the following functions to track mouse movement and rotate an object:
function getAngle(dx, dy) {
var angle
if (dx != 0) {
var radians = Math.atan(dy / dx) + (dx < 0 ? Math.PI : 0)
angle = radiansToDegrees(radians);
if (angle < 0) angle += 360;
} else {
angle = dy > 0 ? 90 : 270;
}
return angle;
}
function getAngleBetweenPoints(p1, p2) {
var dx = p1.x - p2.x
var dy = p1.y - p2.y
return getAngle(dx, dy)
}
$(document).mousemove(function (e) {
if (selectionBounds) {
var midpoint = new pe.Classes.Point(selectionBounds.Left + (selectionBounds.Width / 2), selectionBounds.Top + (selectionBounds.Height / 2));
var mousepoint = new pe.Classes.Point(e.pageX, e.pageY);
var angle = getAngleBetweenPoints(midpoint, mousepoint);
if (lastAngle) {
var diff = angle - lastAngle;
rotate(degreesToRadians(diff));
}
lastAngle = angle;
}
});
This works well, as long as I move the mouse slowly, and as long as the mouse doesn't get too close to the origin (midpoint). Moving too quickly causes additional spin rotations, and coming close to the origin causes unexpected changes of direction.
How can I fix this code? I really just need to know which direction the mouse is moving in (clockwise or anti-clockwise), as I can get an idea of the speed just from the change in mousepoint and then update the rotation based on that.
There are literally dozens of SO threads on topics related to this (How to get the direction (angle) of rectangle after rotating it from a pivot point, How to get cardinal mouse direction from mouse coordinates, Moving a rotated element in the direction of the rotation in JavaScript) - but I haven't been able to find anything that can answer this question, except one comment referring to this requiring the cross product, which I didn't fully understand.
http://jsfiddle.net/wRexz/3/ (click and drag to rotate the rectangle)
var angle = 0, sp = startpoint, mp = midpoint;
var p = {x:e.offsetX, y:e.offsetY};
var sAngle = Math.atan2((sp.y-mp.y),(sp.x - mp.x));
var pAngle = Math.atan2((p.y-mp.y),(p.x - mp.x));
angle = (pAngle - sAngle) * 180/Math.PI;
$("#display").text(angle);
$('#rotateme').css({ rotate: '+=' + angle });
startpoint = {x:p.x, y:p.y};
The concept here is basic trig. You find the angle from 0 of the "start point" and do the same for the "end point" or "current point". Subtract the first from the second, and that is your "delta angle".
You will still get erratic behavior around the midpoint, due to the nature of how rapidly the angles can change. One solution to this is stopping rotation when within a certain distance of the midpoint.
I'm programming a HTML5 < canvas > project that involves zooming in and out of images using the scroll wheel.
I want to zoom towards the cursor like google maps does but I'm completely lost on how to calculate the movements.
What I have: image x and y (top-left corner); image width and height; cursor x and y relative to the center of the canvas.
In short, you want to translate() the canvas context by your offset, scale() it to zoom in or out, and then translate() back by the opposite of the mouse offset. Note that you need to transform the cursor position from screen space into the transformed canvas context.
ctx.translate(pt.x,pt.y);
ctx.scale(factor,factor);
ctx.translate(-pt.x,-pt.y);
Demo: http://phrogz.net/tmp/canvas_zoom_to_cursor.html
I've put up a full working example on my website for you to examine, supporting dragging, click to zoom in, shift-click to out, or scroll wheel up/down.
The only (current) issue is that Safari zooms too fast compared to Chrome or Firefox.
I hope, these JS libraries will help you:
(HTML5, JS)
Loupe
http://www.netzgesta.de/loupe/
CanvasZoom
https://github.com/akademy/CanvasZoom
Scroller
https://github.com/zynga/scroller
As for me, I'm using loupe. It's awesome!
For you the best case - scroller.
I recently needed to archive same results as Phrogz had already done but instead of using context.scale(), I calculated each object size based on ratio.
This is what I came up with. Logic behind it is very simple. Before scaling, I calculate point distance from edge in percentages and later adjust viewport to correct place.
It took me quite a while to come up with it, hope it saves someones time.
$(function () {
var canvas = $('canvas.main').get(0)
var canvasContext = canvas.getContext('2d')
var ratio = 1
var vpx = 0
var vpy = 0
var vpw = window.innerWidth
var vph = window.innerHeight
var orig_width = 4000
var orig_height = 4000
var width = 4000
var height = 4000
$(window).on('resize', function () {
$(canvas).prop({
width: window.innerWidth,
height: window.innerHeight,
})
}).trigger('resize')
$(canvas).on('wheel', function (ev) {
ev.preventDefault() // for stackoverflow
var step
if (ev.originalEvent.wheelDelta) {
step = (ev.originalEvent.wheelDelta > 0) ? 0.05 : -0.05
}
if (ev.originalEvent.deltaY) {
step = (ev.originalEvent.deltaY > 0) ? 0.05 : -0.05
}
if (!step) return false // yea..
var new_ratio = ratio + step
var min_ratio = Math.max(vpw / orig_width, vph / orig_height)
var max_ratio = 3.0
if (new_ratio < min_ratio) {
new_ratio = min_ratio
}
if (new_ratio > max_ratio) {
new_ratio = max_ratio
}
// zoom center point
var targetX = ev.originalEvent.clientX || (vpw / 2)
var targetY = ev.originalEvent.clientY || (vph / 2)
// percentages from side
var pX = ((vpx * -1) + targetX) * 100 / width
var pY = ((vpy * -1) + targetY) * 100 / height
// update ratio and dimentsions
ratio = new_ratio
width = orig_width * new_ratio
height = orig_height * new_ratio
// translate view back to center point
var x = ((width * pX / 100) - targetX)
var y = ((height * pY / 100) - targetY)
// don't let viewport go over edges
if (x < 0) {
x = 0
}
if (x + vpw > width) {
x = width - vpw
}
if (y < 0) {
y = 0
}
if (y + vph > height) {
y = height - vph
}
vpx = x * -1
vpy = y * -1
})
var is_down, is_drag, last_drag
$(canvas).on('mousedown', function (ev) {
is_down = true
is_drag = false
last_drag = { x: ev.clientX, y: ev.clientY }
})
$(canvas).on('mousemove', function (ev) {
is_drag = true
if (is_down) {
var x = vpx - (last_drag.x - ev.clientX)
var y = vpy - (last_drag.y - ev.clientY)
if (x <= 0 && vpw < x + width) {
vpx = x
}
if (y <= 0 && vph < y + height) {
vpy = y
}
last_drag = { x: ev.clientX, y: ev.clientY }
}
})
$(canvas).on('mouseup', function (ev) {
is_down = false
last_drag = null
var was_click = !is_drag
is_drag = false
if (was_click) {
}
})
$(canvas).css({ position: 'absolute', top: 0, left: 0 }).appendTo(document.body)
function animate () {
window.requestAnimationFrame(animate)
canvasContext.clearRect(0, 0, canvas.width, canvas.height)
canvasContext.lineWidth = 1
canvasContext.strokeStyle = '#ccc'
var step = 100 * ratio
for (var x = vpx; x < width + vpx; x += step) {
canvasContext.beginPath()
canvasContext.moveTo(x, vpy)
canvasContext.lineTo(x, vpy + height)
canvasContext.stroke()
}
for (var y = vpy; y < height + vpy; y += step) {
canvasContext.beginPath()
canvasContext.moveTo(vpx, y)
canvasContext.lineTo(vpx + width, y)
canvasContext.stroke()
}
canvasContext.strokeRect(vpx, vpy, width, height)
canvasContext.beginPath()
canvasContext.moveTo(vpx, vpy)
canvasContext.lineTo(vpx + width, vpy + height)
canvasContext.stroke()
canvasContext.beginPath()
canvasContext.moveTo(vpx + width, vpy)
canvasContext.lineTo(vpx, vpy + height)
canvasContext.stroke()
canvasContext.restore()
}
animate()
})
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<canvas class="main"></canvas>
</body>
</html>
I took #Phrogz's answer as a basis and made a small library that enables canvas with dragging, zooming and rotating.
Here is the example.
var canvas = document.getElementById('canvas')
//assuming that #param draw is a function where you do your main drawing.
var control = new CanvasManipulation(canvas, draw)
control.init()
control.layout()
//now you can drag, zoom and rotate in canvas
You can find more detailed examples and documentation on the project's page
Faster
Using ctx.setTransform gives you more performance than multiple matrix calls ctx.translate, ctx.scale, ctx.translate.
No need for complex transformation inversions as and expensive DOM matrix calls tp converts point between zoomed and screen coordinate systems.
Flexible
Flexibility as you don't need to use ctx.save and ctx.restore if you are rendering content at using different transforms. Returning to the transform with ctx.setTransform rather than the potentially frame rate wreaking ctx.restorecall
Easy to invert the transform and get the world coordinates of a (screen) pixel position and the other way round.
Examples
Using mouse and mouse wheel to zoom in and out at mouse position
An example using this method to scale page content at a point (mouse) via CSS transform CSS Demo at bottom of answer also has a copy of the demo from the next example.
And an example of this method used to scale canvas content at a point using setTransform
How
Given a scale and pixel position you can get the new scale as follow...
const origin = {x:0, y:0}; // canvas origin
var scale = 1; // current scale
function scaleAt(x, y, scaleBy) { // at pixel coords x, y scale by scaleBy
scale *= scaleBy;
origin.x = x - (x - origin.x) * scaleBy;
origin.y = y - (y - origin.y) * scaleBy;
}
To position the canvas and draw content
ctx.setTransform(scale, 0, 0, scale, origin.x, origin.y);
ctx.drawImage(img, 0, 0);
To use if you have the mouse coordinates
const zoomBy = 1.1; // zoom in amount
scaleAt(mouse.x, mouse.y, zoomBy); // will zoom in at mouse x, y
scaleAt(mouse.x, mouse.y, 1 / zoomBy); // will zoom out by same amount at mouse x,y
To restore the default transform
ctx.setTransform(1,0,0,1,0,0);
The inversions
To get the coordinates of a point in the zoomed coordinate system and the screen position of a point in the zoomed coordinate system
Screen to world
function toWorld(x, y) { // convert to world coordinates
x = (x - origin.x) / scale;
y = (y - origin.y) / scale;
return {x, y};
}
World to screen
function toScreen(x, y) {
x = x * scale + origin.x;
y = y * scale + origin.y;
return {x, y};
}