Dragging a rectangle in Raphael JS bounces back and forth - javascript

In this jsFiddle I have a Raphael JS grid with a rectangle that I need to move snapped to a grid. The rectangle has four red handles in each corner, and when it moves the handles move as well.
So far I can move the rectangle around (that works fine) but when I try to move it to the left the rectangle flickers and bounces back and forth. Could the problem be that I'm setting the x rectangle coordinate inside the drag move function? Any ideas will be greatly appreciated.
var move = function(dx, dy) {
rect.attr("x", ox + dx);
rect.attr("y", oy + dy);
leftTop.attr("x", ox1 + dx);
leftTop.attr("y", oy1 + dy);
rightTop.attr("x", ox2 + dx);
rightTop.attr("y", oy2 + dy);
leftBottom.attr("x", ox3 + dx);
leftBottom.attr("y", oy3 + dy);
rightBottom.attr("x", ox4 + dx);
rightBottom.attr("y", oy4 + dy);
if ((dx - lastdx) < 0)
seeMoveLeft(rect, leftTop, rightTop,
leftBottom, rightBottom);
lastdx = dx;
};
var up = function() {};
rect.drag(move, start, up);
var seeMoveLeft = function (rect, leftTop, rightTop,
leftBottom, rightBottom){
var left = rect.attr('x');
// find next left grid
var found = false;
var min = left - 40;
for (var i=left; i>=min; i--){
if (i % 40 == 0) {
found = true;
break;
}
}
if (found) {
var diff = left - i;
rect.attr('x', i);
var lt = leftTop.attr('x');
leftTop.attr('x', lt - diff);
var rt = rightTop.attr('x');
rightTop.attr('x', rt - diff);
var lb = leftBottom.attr('x');
leftBottom.attr('x', lb - diff);
var rb = rightBottom.attr('x');
rightBottom.attr('x', rb - diff);
}
}

The problem is that you set the new x of rect here:
rect.attr("x", ox + dx);
Then you modify it here:
if ((dx - lastdx) < 0)
seeMoveLeft(rect, leftTop, rightTop,
leftBottom, rightBottom);
But since move function is based on the mousemove event, sometimes, you'll get the same dx value 2 times in a row. This is normal with mousemove event, especially if you move slow. You can try it below, each time the clientX stays the same, the window will turn green.
var lastClientX;
window.addEventListener('mousemove', (e) => {
if (lastClientX && e.clientX === lastClientX) {
document.body.style.backgroundColor = 'green';
} else {
document.body.style.backgroundColor = 'yellow';
}
lastClientX = e.clientX;
})
body {
width: 100%;
height 100%;
}
What happens in your case when you have 2 consecutive identical dx is that x - lastdx won't validate and so the position won't be adjusted and will stay at rect.attr("x", ox + dx);. So first move event, the position is adjusted to the grid with seeMoveLeft, next, the position changes but isn't adjusted because dx is not smaller than lastdx, it's equal. Hence the flicker you see.
Simplest way to correct, would be to skip the positionning if dx is the same as lastdx. Like this:
if(lastdx !== dx){
rect.attr("x", ox + dx);
leftTop.attr("x", ox1 + dx);
rightTop.attr("x", ox2 + dx);
leftBottom.attr("x", ox3 + dx);
rightBottom.attr("x", ox4 + dx);
}
https://jsfiddle.net/ce7sh9ov/1/

Related

Calculate angle based on x, y position

I am trying to calculate the angle for an arrow on a ball, based on the position where it is going to.
The arrow moves, but in a total unexplainable direction, can anybody give some pointers?
Codepen available: Codepen
I added the full code on here (EDITED based on input):
I added a step to make the difference bigger for the angle calculation, not sure if that is the right way to go, but it seems a bit more functional. Plus added the +/- 90 in the angle method, but that doesnt seem to fix it. It is still feeling odd.
class Throwable {
constructor(){
this.throwObject = null;
this.canDrag = null;
this.initialDiffX = 0;
this.initialDiffY = 0;
this.previousX = 0;
this.previousY = 0;
this.intervalCounter = 0;
}
set x(input) {
this.throwObject.style.left = input + 'px';
}
set y(input) {
this.throwObject.style.top = input + 'px';
}
set rotation(input) {
this.throwObject.style.transform = `rotate(${input}deg)`;
}
init(){
this.throwObject = document.querySelector('.throwable');
this.throwObject.addEventListener('mousedown', this.activateDrag.bind(this));
this.throwObject.addEventListener('mouseup', this.deactivateDrag.bind(this));
document.addEventListener('mousemove', this.drag.bind(this));
}
activateDrag(event) {
this.canDrag = true;
this.initialDiffX = event.clientX - this.throwObject.offsetLeft;
this.initialDiffY = event.clientY - this.throwObject.offsetTop;
}
deactivateDrag() {
this.canDrag = false;
}
drag(event) {
if(this.canDrag === true) {
if(this.intervalCounter >= 30) {
this.intervalCounter = 0;
}
if(this.intervalCounter === 0) {
this.previousX = event.clientX;
this.previousY = event.clientY;
}
this.intervalCounter++;
this.y = event.clientY- this.initialDiffY;
this.x = event.clientX - this.initialDiffX;
this.rotation = this.angle(event.clientX, event.clientY, this.previousX, this.previousY);
}
}
angle(ex, ey, cx, cy) {
var dy = ey - cy;
var dx = ex - cx;
return Math.atan2(dy, dx) * 180 / Math.PI + 90;
}
// Untility
log(logObject) {
let logStr = '';
for(let key in logObject) {
logStr += `${key}: ${logObject[key]}<br>`;
}
document.getElementById('log').innerHTML = logStr;
}
}
let throwable = new Throwable();
throwable.init();
I made a mistake in comparing two different values, I fixed that, it is working way better, still have some odd behavior sometimes, seems like it doesnt know where to go in some points. But working better than before.
Maybe you have some mistakes in your angle function. This works for me:
angle(cx, cy, ex, ey) {
var dy = ey - cy ;
var dx = cx - ex ;
return Math.atan2(dx, dy) * 180 / Math.PI;
}
When you call this.angle() you give it twice this.throwObject.offset..., once directly and once via px and py:
let px = this.throwObject.offsetLeft;
let py = this.throwObject.offsetTop;
this.rotation = this.angle(this.throwObject.offsetLeft, this.throwObject.offsetTop, px, py)
That will result in dx and dy to be 0 in angle() making the result of Math.atan2() unpredictable.
I'm not sure about the rest of your code, but maybe you meant to call angle() like this:
this.rotation = this.angle(this.x, this.y, px, py);
There are a couple small issues that I can see.
First, the angle method is calculating radians in range of -180 to 180 and you want it to be 0 to 360. So after angle calculation you'll want to convert something like this:
angle(ex, ey, cx, cy) {
var dy = ey - cy;
var dx = ex - cx;
var theta = Math.atan2(dy, dx) * 180 / Math.PI;
if (theta < 0) theta += 360; // convert to [0, 360]
return theta;
}
Second, the starting angle of your element at 0 degrees is not the actual 0 degrees calculated by this method due to how js coordinates work. A quick fix is to add 90 degrees to make it match:
set rotation(input) {
this.throwObject.style.transform = `rotate(${input + 90}deg)`;
}
It's still a little janky after these conversion but I think it's a start on the right calculations. My guess is part of the issue is having such close points for calculation.
This happens because there's a difference how angles are measured between Math.atan2() and the CSS rotate transformation.
For us humans it's natural that the 12 o' clock position on an analog clock refers to the angle 0 - same for CSS rotate.
Math.atan2() however measures the angle starting from the horizontal x axis. So depending on your input coordinates it would be the 3 or 9 o' clock position.
There's an easy fix however.
After calculating the angle
Math.atan2(dy, dx) * 180 / Math.PI
just subtract 90 degrees like
Math.atan2(dy, dx) * 180 / Math.PI - 90
What happens when intervalCounter become 0? The previus point moved to the event point, so dy, dx becomes 0 and you have a jitter: -180 + 90, +180 + 90, 0 + 90 as defined in Math.atan2. After that, the previus point is fixed until intervalCounter < 30 and you have some inceasing distance between the previus and event points, so the angle is close to the expected one.
Anyway, this is a bad coordinate filter. You can improve it by implementing simple exponential filtering or by using fixed size (30 in your case) queue for event point.

Mouse wheel event has jittery zoom/scale in JointJS

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/

Javascript create SVG path bottom up vs top down

I have a page that shows a grid of job positions and I am showing the progression from one to another by using SVG + paths to draw the connection between boxes.
My code is working just fine when I am connecting an element at the top to one at the bottom. It is finding the XY of the top box and the XY of the bottom box and connects the two.
My issue is I want to flip this code and go from the bottom up. This means I need the top XY of the bottom element and the bottom XY of the top element and draw the path.
I have been trying to flip offsets around and basically do the opposite of what is working but I think my math is wrong somewhere.
Here is what the top down approach looks like. Works just fine.
The bottom up approach however is not correct. Theres some math errors somewhere and the calculations are causing the SVG to be cut off.
I believe the answer lies within the connectElements() function as that is where the coordinates are determined.
Any thoughts on how I can get these calculations corrected?
Fiddle: http://jsfiddle.net/Ly59a2hf/2/
JS Code:
function getOffset(el) {
var rect = el.getBoundingClientRect();
return {
left: rect.left + window.pageXOffset,
top: rect.top + window.pageYOffset,
width: rect.width || el.offsetWidth,
height: rect.height || el.offsetHeight
};
}
function drawPath(svg, path, startX, startY, endX, endY) {
// get the path's stroke width (if one wanted to be really precize, one could use half the stroke size)
var style = getComputedStyle(path)
var stroke = parseFloat(style.strokeWidth);
// check if the svg is big enough to draw the path, if not, set heigh/width
if (svg.getAttribute("height") < endY) svg.setAttribute("height", endY);
if (svg.getAttribute("width") < (startX + stroke)) svg.setAttribute("width", (startX + stroke));
if (svg.getAttribute("width") < (endX + stroke * 3)) svg.setAttribute("width", (endX + stroke * 3));
var deltaX = (endX - startX) * 0.15;
var deltaY = (endY - startY) * 0.15;
// for further calculations which ever is the shortest distance
var delta = deltaY < absolute(deltaX) ? deltaY : absolute(deltaX);
// set sweep-flag (counter/clock-wise)
// if start element is closer to the left edge,
// draw the first arc counter-clockwise, and the second one clock-wise
var arc1 = 0;
var arc2 = 1;
if (startX > endX) {
arc1 = 1;
arc2 = 0;
}
// draw tha pipe-like path
// 1. move a bit down, 2. arch, 3. move a bit to the right, 4.arch, 5. move down to the end
path.setAttribute("d", "M" + startX + " " + startY +
" V" + (startY + delta) +
" A" + delta + " " + delta + " 0 0 " + arc1 + " " + (startX + delta * signum(deltaX)) + " " + (startY + 2 * delta) +
" H" + (endX - delta * signum(deltaX)) +
" A" + delta + " " + delta + " 0 0 " + arc2 + " " + endX + " " + (startY + 3 * delta) +
" V" + (endY - 30));
}
function connectElements(svg, path, startElem, endElem, type, direction) {
// Define our container
var svgContainer = document.getElementById('svgContainer'),
svgTop = getOffset(svgContainer).top,
svgLeft = getOffset(svgContainer).left,
startX,
startY,
endX,
endY,
startCoord = startElem,
endCoord = endElem;
console.log(svg, path, startElem, endElem, type, direction)
/**
* bottomUp - This means we need the top XY of the starting box and the bottom XY of the destination box
* topDown - This means we need the bottom XY of the starting box and the top XY of the destination box
*/
switch (direction) {
case 'bottomUp': // Not Working
// Calculate path's start (x,y) coords
// We want the x coordinate to visually result in the element's mid point
startX = getOffset(startCoord).left + 0.5 * getOffset(startElem).width - svgLeft; // x = left offset + 0.5*width - svg's left offset
startY = getOffset(startCoord).top + getOffset(startElem).height - svgTop; // y = top offset + height - svg's top offset
// Calculate path's end (x,y) coords
endX = endCoord.getBoundingClientRect().left + 0.5 * endElem.offsetWidth - svgLeft;
endY = endCoord.getBoundingClientRect().top - svgTop;
break;
case 'topDown': // Working
// If first element is lower than the second, swap!
if (startElem.offsetTop > endElem.offsetTop) {
var temp = startElem;
startElem = endElem;
endElem = temp;
}
// Calculate path's start (x,y) coords
// We want the x coordinate to visually result in the element's mid point
startX = getOffset(startCoord).left + 0.5 * getOffset(startElem).width - svgLeft; // x = left offset + 0.5*width - svg's left offset
startY = getOffset(startCoord).top + getOffset(startElem).height - svgTop; // y = top offset + height - svg's top offset
// Calculate path's end (x,y) coords
endX = endCoord.getBoundingClientRect().left + 0.5 * endElem.offsetWidth - svgLeft;
endY = endCoord.getBoundingClientRect().top - svgTop;
break;
}
// Call function for drawing the path
drawPath(svg, path, startX, startY, endX, endY, type);
}
function connectAll(direction) {
var svg = document.getElementById('svg1'),
path = document.getElementById('path1');
// This is just to help with example.
if (direction == 'topDown') {
var div1 = document.getElementById('box_1'),
div2 = document.getElementById('box_20');
} else {
var div1 = document.getElementById('box_20'),
div2 = document.getElementById('box_1');
}
// connect all the paths you want!
connectElements(svg, path, div1, div2, 'line', direction);
}
//connectAll('topDown'); // Works fine. Path goes from the bottom of box_1 to the top of box_20
connectAll('bottomUp'); // Doesn't work. I expect path to go from top of box_20 to the bottom of box_1
IMO, you can simplify things by making the SVG the exact right size. Ie. fit it between the two elements vertically, and have it start at the leftmost X coord.
If you do that, the path starts and ends at either:
X: 0 or svgWidth
Y: 0 or svgHeight.
Then as far as drawing the path goes, it's just a matter of using the relative directions (startX -> endX and startY -> endY) in your calculations. I've called these variables xSign and ySign. If you are consistent with those, everything works out correctly.
The last remaining complication is working out which direction the arcs for the rounded corners have to go - clockwise or anticlockwise. You just have to work out the first one, and the other one is the opposite.
function getOffset(el) {
var rect = el.getBoundingClientRect();
return {
left: rect.left + window.pageXOffset,
top: rect.top + window.pageYOffset,
width: rect.width || el.offsetWidth,
height: rect.height || el.offsetHeight
};
}
function drawPath(svg, path, start, end) {
// get the path's stroke width (if one wanted to be really precise, one could use half the stroke size)
var style = getComputedStyle(path)
var stroke = parseFloat(style.strokeWidth);
var arrowHeadLength = stroke * 3;
var deltaX = (end.x - start.x) * 0.15;
var deltaY = (end.y - start.y) * 0.15;
// for further calculations which ever is the shortest distance
var delta = Math.min(Math.abs(deltaX), Math.abs(deltaY));
var xSign = Math.sign(deltaX);
var ySign = Math.sign(deltaY);
// set sweep-flag (counter/clock-wise)
// If xSign and ySign are opposite, then the first turn is clockwise
var arc1 = (xSign !== ySign) ? 1 : 0;
var arc2 = 1 - arc1;
// draw tha pipe-like path
// 1. move a bit vertically, 2. arc, 3. move a bit to the horizontally, 4.arc, 5. move vertically to the end
path.setAttribute("d", ["M", start.x, start.y,
"V", start.y + delta * ySign,
"A", delta, delta, 0, 0, arc1, start.x + delta * xSign, start.y + 2 * delta * ySign,
"H", end.x - delta * xSign,
"A", delta, delta, 0, 0, arc2, end.x, start.y + 3 * delta * ySign,
"V", end.y - arrowHeadLength * ySign].join(" "));
}
function connectElements(svg, path, startElem, endElem, type, direction) {
// Define our container
var svgContainer = document.getElementById('svgContainer');
// Calculate SVG size and position
// SVG is sized to fit between the elements vertically, start at the left edge of the leftmost
// element and end at the right edge of the rightmost element
var startRect = getOffset(startElem),
endRect = getOffset(endElem),
pathStartX = startRect.left + startRect.width / 2,
pathEndX = endRect.left + endRect.width / 2,
startElemBottom = startRect.top + startRect.height,
svgTop = Math.min(startElemBottom, endRect.top + endRect.height),
svgBottom = Math.max(startRect.top, endRect.top),
svgLeft = Math.min(pathStartX, pathEndX),
svgHeight = svgBottom - svgTop;
// Position the SVG
svg.style.left = svgLeft + 'px';
svg.style.top = svgTop + 'px';
svg.style.width = Math.abs(pathEndX - pathStartX) + 'px';
svg.style.height = svgHeight + 'px';
// Call function for drawing the path
var pathStart = {x: pathStartX - svgLeft, y: (svgTop === startElemBottom) ? 0 : svgHeight};
var pathEnd = {x: pathEndX - svgLeft, y: (svgTop === startElemBottom) ? svgHeight : 0};
drawPath(svg, path, pathStart, pathEnd);
}
function connectAll(direction) {
var svg = document.getElementById('svg1'),
path = document.getElementById('path1');
// This is just to help with example.
if (direction == 'topDown') {
var div1 = document.getElementById('box_1'),
div2 = document.getElementById('box_20');
} else {
var div1 = document.getElementById('box_20'),
div2 = document.getElementById('box_1');
}
// connect all the paths you want!
connectElements(svg, path, div1, div2, 'line');
}
//connectAll('topDown');
connectAll('bottomUp');
http://jsfiddle.net/93Le85tk/3/

zoom changes slider behavior css/javascript

I have created a circle slider using JavaScript, and I need it to act right if it gets zoomed in or out.
My issue is when the circle slider gets zoomed in eg. (zoom: 0.5) , the mouse event listener for the slider will not act probably.
This issue only happen if I set the the zoom property to less or bigger than 1 .
You can try and see the differences: https://jsfiddle.net/mqgfxkjf/8/
Change:
<div style="zoom: 1.0">
To:
<div style="zoom: 0.5">
And you will find that it's not acting right while moving the slider to all-directions.
Tested on Chrome
You have to scale the mouse position accordingly to the zoom value.
Let's say you have set zoom value to 0.5, you will have to scale the mouse position (x and y) with the same value. So in order to fix this exact problem, you can do something as simple as just dividing by the scale value: var mPos = {x: (e.clientX / 0.5) - elPos.x, y: (e.clientY / 0.5) - elPos.y };.
I highly suggest that you let the script handle the scale / zoom value so that you can set it as a variable in your script. I.e. something like this:
(function () {
var scaleValue = 0.5;
addZoom(scaleValue);
var $container = $('#container');
var $slider = $('#slider');
var sliderW2 = $slider.width()/2;
var sliderH2 = $slider.height()/2;
var radius = 200;
var deg = 0;
var elP = $('#container').offset();
var elPos = { x: elP.left, y: elP.top};
var X = 0, Y = 0;
var mdown = false;
$('#container')
.mousedown(function (e) { mdown = true; })
.mouseup(function (e) { mdown = false; })
.mousemove(function (e) {
if (mdown) {
var mPos = {x: (e.clientX / scaleValue) - elPos.x, y: (e.clientY / scaleValue) - elPos.y };
var atan = Math.atan2(mPos.x-radius, mPos.y-radius);
deg = -atan/(Math.PI/180) + 180; // final (0-360 positive) degrees from mouse position
X = Math.round(radius* Math.sin(deg*Math.PI/180));
Y = Math.round(radius* -Math.cos(deg*Math.PI/180));
$slider.css({ left: X+radius-sliderW2, top: Y+radius-sliderH2 });
// AND FINALLY apply exact degrees to ball rotation
$slider.css({ WebkitTransform: 'rotate(' + deg + 'deg)'});
$slider.css({ '-moz-transform': 'rotate(' + deg + 'deg)'});
//
// PRINT DEGREES
$('#value').html('angle deg= '+deg);
}
});
})();
function addZoom(scaleValue) {
$('#zoom-container').css('zoom', scaleValue);
}
Fiddle:
https://jsfiddle.net/mqgfxkjf/10/

Zoom Canvas to Mouse Cursor

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};
}

Categories