Move image around (css3 transform) with touchmove on iPad - javascript

I have an image which I would like to move around on my iPad3
The problem is that it isn't going as good as I hoped for, the image doesn't move smooth and is moving behind the gesture.
What I have is as follows (3MB base64 image)
<img src="data:image/jpeg;base64,/9j/4AAQ....">
css:
img {
transform: translate3d(0,0,0);
}
And the javascript is
img.on('touchstart', function (e) {
var diffX = e.pageX;
var diffY = e.pageY;
img.on('touchmove', function (e) {
translateX += e.pageX - diffX;
translateY += e.pageY - diffY;
img.css({'-webkit-transform': 'translate(' + translateX + 'px, ' + translateY + 'px)'});
diffX = e.pageX;
diffY = e.pageY;
});
return false;
})
...
It works great on my laptop, but not my iPad3.
I also tried requestAnimationFrame, but then nothing happens until I stop moving. Any suggestion how to improve the performance on my iPad ?

This does most of the math outside of the touchmove function
and sets the webkittransform directly without passing by a very long jquery css function.
it also uses the 3d transition witch isn't properly set with just adding translate3d in css file with the ios7
var sx,sy,cx=0,cy=0,img=document.images[0];
img.addEventListener('touchstart',ts,false);
img.addEventListener('touchmove',tm,false);
img.addEventListener('touchend',te,false);
function ts(e){
e.preventDefault();
sx=e.pageX-cx;
sy=e.pageY-cy;
}
function tm(e){
this.style.webkitTransform='translate3d('+
(e.pageX-sx)+'px,'+(e.pageY-sy)+'px,0)';
}
function te(e){
cx=e.pageX-sx;
cy=e.pageY-sy;
}
another point is ... even if you have the ipad 3 it can't handle a big image like that so consider putting all inside a div with overflow:hidden this will increase the performance too.
div{
width:400px;/*try 100%*/
height:400px;/*try 100%*/
overflow:hidden;
}
Mouse move example (not touch but its the same except you don't need the isup check)
http://jsfiddle.net/AtBUh/

Related

Drag/Reposition Element On touchmove not working

I have a fixed window on my screen that I would like the user to be able to drag around the screen. While I have set this up to work for mouse inputs, I am having more difficulty getting this to work for touch screens.
So I have a basic box like so:
<div id="smallavatar" class="smallbox">
</div>
Which is then immediately followed by this JS (note that the first half is for the click events)
var divOverlay = document.getElementById ("smallavatar");
var isDown = false;
divOverlay.addEventListener('mousedown', function(e) {
isDown = true;
}, true);
document.addEventListener('mouseup', function() {
isDown = false;
}, true);
document.addEventListener('mousemove', function(event) {
event.preventDefault();
if (isDown) {
var deltaX = event.movementX;
var deltaY = event.movementY;
var rect = divOverlay.getBoundingClientRect();
divOverlay.style.left = rect.x + deltaX + 'px';
divOverlay.style.top = rect.y + deltaY + 'px';
}
}, true);
divOverlay.addEventListener('touchstart', e => {
clientX = e.touches[0].screenX;
clientY = e.touches[0].screenY;
});
divOverlay.addEventListener('touchmove', e => {
let x = divOverlay.style.left;
let y = divOverlay.style.top;
// Compute the change in X and Y coordinates.
// The first touch point in the changedTouches
// list is the touch point that was just removed from the surface.
deltaX = e.changedTouches[0].clientX - clientX;
deltaY = e.changedTouches[0].clientY - clientY;
divOverlay.style.left = divOverlay.style.left + deltaX;
divOverlay.style.top = divOverlay.style.top + deltaY;
});
Finally the following CSS is being used:
.smallbox{position:fixed; bottom:70px; right:0; width:360px; height:400px; z-index:20;}
Now while the touchmove event does work, the problem is that the box seems to fly off the screen very quickly. The idea is supposed to be that I'm trying to get the position the div was using before the touch event started, then work out how much movement has occured in the touchmove event and then from that update the left and top values with the new position it should be in.
Is there anything wrong that would explain why this isn't working as expected?
You have one major flaw in your code that causes the unexpected result:
At touchstart you store clientX and clientY, and than during touchmove you keep referencing those two values at deltaX = e.changedTouches[0].clientX - clientX; (and Y).
But while e.changedTouches[0].clientX keeps updating, clientX never gets updated and always keeps its initial start-value.
So for the next frame/iteration, deltaX = e.changedTouches[0].clientX - clientX; will actually be the delta-x of that last frame, plus the delta-x of the frame before, and the one before, and before, and so on till the very first frame.
So your divOverlay will be moving exponentially, and be out of sight in a fraction of a sec.
What the best choice is for getting the current position of divOverlay, depends a little on your situation, although I think in most cases, using pageX/pageY is probably your safest bet.
The other options are clientX/clientY and screenX/screenY, see this and this article for the differences between the three.
In any case, I wouldn't recommend using them interchangeably during one calculation, unless it's absolutely necessary.
See the live snippet below for the solution:
var divOverlay = document.getElementById("smallavatar");
/*MOUSE-LISTENERS---------------------------------------------*/
var isDown=false;
divOverlay.addEventListener('mousedown',function(){isDown=true;},true);
document.addEventListener('mouseup',function(){isDown=false;},true);
document.addEventListener('mousemove',function(e) {
e.preventDefault();
if (isDown) {
divOverlay.style.left = divOverlay.offsetLeft + e.movementX + 'px';
divOverlay.style.top = divOverlay.offsetTop + e.movementY + 'px';
}
},true);
/*TOUCH-LISTENERS---------------------------------------------*/
var startX=0, startY=0;
divOverlay.addEventListener('touchstart',function(e) {
startX = e.changedTouches[0].pageX;
startY = e.changedTouches[0].pageY;
});
divOverlay.addEventListener('touchmove',function(e) {
e.preventDefault();
var deltaX = e.changedTouches[0].pageX - startX;
var deltaY = e.changedTouches[0].pageY - startY;
divOverlay.style.left = divOverlay.offsetLeft + deltaX + 'px';
divOverlay.style.top = divOverlay.offsetTop + deltaY + 'px';
//reset start-position for next frame/iteration
startX = e.changedTouches[0].pageX;
startY = e.changedTouches[0].pageY;
});
.smallbox{position:fixed; bottom:70px; right:0; width:36px; height:40px; z-index:20; background:red;}
<div id="smallavatar" class="smallbox"></div>
jsfiddle: https://jsfiddle.net/2hdczkwn/4/
To address your major flaw, I added startX = e.changedTouches[0].pageX; and startY = e.changedTouches[0].pageY; to the end of your touchmove listener, resetting the start-position for each new frame/iteration to the end-position of the last frame/iteration.
I also added e.preventDefault(); to your touchmove listener, because otherwise any scrollable page would also start scrolling while you were dragging the divOverlay.
I converted your arrow functions into traditional ones, like your mouse listeners.
I added var startX=0, startY=0; outside the functions to make sure they are global vars.
I replaced var rect = divOverlay.getBoundingClientRect(); and rect.x and rect.y inside your mousemove listener, and divOverlay.style.left and divOverlay.style.top inside your touchmove listener, with divOverlay.offsetLeft and divOverlay.offsetTop.
This is actually quite important, since divOverlay.style.left returns a px value, e.g. 57px. When this value is used in a calculation, like 57px + 12, it will not result in 69 or 69px but instead in NaN.
I can't help but notice that your mouse and touch listeners are written in a different coding style, mouse uses traditional JS, while touch is written in the new ES6, using let and arrow functions.
As if you copied the touch listeners from someone else and didn't change it to match the rest of your code.
While it is fine to use either style and to use other people's code (as long as you have permission), I would discourage using them both in the same project, and it is never a good idea to simply copy someone else's code without rewriting it to fit your own style.
This will make sure your whole project retains its current style of coding, and has the added advantage of you actually understanding the code you're using.

Stopping image from scrolling paraScrolling

edit- I actually had my image originally position:relative. I have fixed that in my code. I would like the image to scroll left until it has disappeared from the window. I would like it to stop moving, or even reset. I can do that part. I used the developer window in chrome to check, and the position:right of the image in question moves on well past 1700px, which I tried to stop with my if block in paraScrollRight
I'm trying to get an image to stop moving, so that I can get another image to move while the user scrolls down the page. For some reason, my if logic doesn't stop scrolling at all.
var yPos, image;
function paraScrollDown(){
yPos = window.pageYOffset;
image = document.getElementById("image");
image.style.top = (yPos * 1.0) + "px";
}
function paraScrollRight(){
yPos = window.pageYOffset;
image = document.getElementById("image");
if(image.style.right <= 1,374 + "px") {
image.style.right = (yPos * 2.7) + "px";
}
}
window.addEventListener("scroll",paraScrollRight);
<img id="image" style="position:relative" src="https://s-media-cache-ak0.pinimg.com/236x/ee/94/32/ee94322ba44eebc686d2e8381a84259c.jpg" />
Try this: https://jsfiddle.net/92rse23e/
I only handled the paraScrollDown method since that's what I understood what you needed to be taken care of. An important thing you needed to add was to make the image position: absolute; in CSS.

mouseMove very laggy

I am trying to obtain the image effect that 99designs is obtaining when hovering a mouse over a design.. [99designs.ca] Logo design contest: Runningbug Needs Logo 220626
I am currently obtaining the position of the mouse on mousemove, then using that to move my popover <img>, and everything works fine, but it is very laggy.. and presumably its from so many calls being made.
To get the position of the mouse:
jQuery(document).ready(function(){
//$("#special").click(function(e){
$(".imgWrap").mousemove(function(e){
//$('#status2').html(e.pageX +', '+ e.pageY);
//alert(e.pageX + ', ' + e.pageY);
mouseX = e.pageX;
mouseY = e.pageY;
});
})
I'm not sure of another way I can do this.. any ideas?
On the full course of events is the following:
User mouses over an img tag.
I get the position of the mouse as per above.
The <img> tag also calls a js function which changes the position of an img tag to the position of the mouse.
Actually, you can check it here: pokemonsite
update: I see there is a bounty placed (thanks !). I'm a little busy at the moment and can't check all the other answers, but I'll make sure to check them asap
There are several ways to improve performance when using mousemove events.
Use backface-visibility: hidden on popover element to force hardware acceleration. Same thing can be achived with transform: translate3d(0,0,0) but that makes difficult to use CSS transform function (see point #2).
Use CSS transform function for absolute positioning to avoid repaints but keep popover element absolute or fixed positioned.
When setting inline CSS via JS use requestAnimationFrame to avoid unnecesary layout trashing.
(maybe, optionally) hide cursor when hovering and use popover element as position indicator.
Move everything you can from JS to CSS ie. :hover state can be used to toggle display of popover element.
I made demo example combining all things listed. There is still some latency between cursor position and popover image and none of example links in original question work so I can't compare against it but I hope someone finds this useful.
DEMO
<div id="imgHolder" class="imgHolder">
<img src="//placehold.it/200x200" alt="" />
</div>
<div id="bigImgHolder" class="imgHover">
<img src="//placehold.it/500x500" alt="" />
</div>
.imgHover {
display: none;
backface-visibility: hidden;
position: fixed;
top: 0; left: 0;
pointer-events: none;
}
.imgHolder:hover ~ .imgHover { display: block; }
// uncomment if it makes sense
//.imgHolder:hover { cursor: none; }
var posX, posY;
$('#imgHolder').mousemove(HoverImg);
function HoverImg(e) {
posX = e.pageX;
posY = e.pageY;
window.requestAnimationFrame(showBigImg);
}
function showBigImg() {
$('#bigImgHolder').css({'-webkit-transform': 'translateX(' + posX + 'px) translateY(' + posY + 'px)', 'transform': 'translateX(' + posX + 'px) translateY(' + posY + 'px)' });
}
references:
http://davidwalsh.name/translate3d
http://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/
https://css-tricks.com/using-requestanimationframe/
Try this:
jQuery(document).ready(function(){
$(".imgWrap").mousemove(function(e){
e.stopPropagation();
mouseX = e.pageX;
mouseY = e.pageY;
});
})
Use e.offsetX and e.offsetY or (recommended) e.clientX and e.clientY instead of pageX and pageY. Maybe this will be a better solution. Note: offsetx and offsety do not work in Firefox as far as I know.
If the absolute (x, y) position is not so important (meaning: some pixel-values can be omitted without destroying your logic), you could try to skip some frames of your mousemove-event.
var globalSkipCounter = 0;
var globalSkipRate = 5;
$(".imgWrap").mousemove(function(e){
if(globalSkipCounter >= globalSkipRate){
var mouseX = e.pageX;
var mouseY = e.pageY;
do_stuff(mouseX, mouseY);
globalSkipCounter = 0;
}
else{
globalSkipCounter+=1;
}
});
This way, you omit redrawing your image on every mousemove-event, instead your draw-routines (do_stuff) are only invoked, once every 5 events.
Cache the position and wrap the update in an if(oldpos !== newpos) type check (remembering to update oldpos inside it).
Use requestAnimationFrame to handle the update - if you have a normal function and pass that as the callback then it will only get called once per frame (ie, don't use an anonymous function).
Finally make use of transform:translate(x,y) to set the position and make better use of the GPU etc. Related to this, there's no harm in making use of the css will-change keyword if you want to use top/left instead.
try a maximum event per second based approach:
jQuery(document).ready(function(){
var now, then, delta, interval = 1000/60; //maximum 60 eps, you can change
//$("#special").click(function(e){
$(".imgWrap").mousemove(function(e){
now = Date.now();
delta = now - then;
if (delta > interval) {
then = now - delta % interval; //subtract extra waited time
//$('#status2').html(e.pageX +', '+ e.pageY);
//alert(e.pageX + ', ' + e.pageY);
mouseX = e.pageX;
mouseY = e.pageY;
// do your thing
}
});
})
EDIT: didn't know then is a reserved word in javascript, you can rename it.
I have a sortable listview in angular, but dragging items with the mouse in chrome was lagging a lot. I tried disabling all chrome extensions and now the lag is totally gone.
It turned out that TamperMonkey was causing it.
Instead of using "left" or "right" property of CSS rather try to use
"transform" I was trying to do the same thing as asked in question, and using "transform" worked for me like a charm.
for example:
transform: translate(30px);
this will move the element, 30px to the right.
by using transform we can move elements to left, right, top and bottom according to the need.

iOS6 JavaScript touchmove event pass through vertical scroll afterwards jQuery animate does not fire

I have a div with a javascript touchmove event listener that scrolls the image inside the div horizontally on iOS6 Mobile Safari. I'd like allow vertical scrolling of the page to bubble up to the browser but when this occurs, jQuery.animate no longer works.
I've posted a simplified version of the code that demonstrates the problem at
https://gist.github.com/4047733
The steps I take to recreate the problem are:
Swipe picture left/right and notice how it animates back to the left edge
Touch the picture and scroll the page up/down
Repeat left/right swipe and notice the picture does NOT animate back to the left edge. It appears jQuery animate fails after touchmove occurs without e.preventDefault
Here is the javascript inside jQuery document ready from the gist link above
var el = document.getElementById("swipebox"),
$slider = $('#swipebox').find('img'),
startX, startY, dx, dy,
startLeft,
animateH = false,
animateV = false;
var onTouchStart = function(e) {
startLeft = parseInt($slider.css('left'), 10) || 0;
startX = e.touches[0].pageX;
startY = e.touches[0].pageY;
};
var onTouchMove = function(e) {
dx = e.touches[0].pageX - startX;
dy = e.touches[0].pageY - startY;
if (
animateH ||
(!animateV && Math.abs(dx) > 5)
) {
// prevent default, we are scrolling horizontally,
animateH = true;
$slider.stop().css({'left': startLeft+dx*2});
e.preventDefault();
} else if (Math.abs(dy) > 5) {
// do NOT prevent default, we are scrolling the page vertically
animateV = true;
} else {
// direction of scroll is undetermined at this time
// we've moved less than 5px in any direction
e.preventDefault();
}
return false;
};
var onTouchEnd = function(e) {
$slider.stop().animate({'left': 0}); // animate image back to left
e.preventDefault();
animateH = false;
animateV = false;
};
var onTouchCancel = function(e) {
console.log('onTouchCancel');
};
el.addEventListener('touchstart', onTouchStart, false);
el.addEventListener('touchmove', onTouchMove, false);
el.addEventListener('touchend', onTouchEnd, false);
el.addEventListener("touchcancel", onTouchCancel, false);
Any insight would be greatly appreciated.
This is bug in iOS6. jQuery animate timers fail when scrolling window in iOS6.
Currently there are few workarounds on this:
Create your own timer functions like someone did: https://gist.github.com/3755461
Use CSS3 transition instead of jQuery.animate. This is preffered way - css3 transitions doesn't have such problem. You can use this jquery plugin http://ricostacruz.com/jquery.transit/ to easily manipulate CSS transitions in JavaScript.

How to drag a DIV so its width and height are negative values?

I'm a bit stumped here. I am developing a feedback utility that will allow the user to "draw" boxes on a web page to highlight problem areas. Right now I have an overlay DIV that fills the screen and jQuery allows you to draw red outlined DIVs by clicking and dragging.
Here is the JS:
{
var $feedbackOverlay = jQuery('#feedbackOverlay');
var $original = { top: 0, left:0 };
$feedbackOverlay.bind('mousedown', function (e)
{
jQuery('<div id="currentHighlight"></div>')
.css('width', '1px')
.css('height', '1px')
.css('border', 'solid 3px #ff0000')
.css('border-radius', '5px')
.css('position', 'absolute')
.css('left', e.pageX)
.css('top', e.pageY)
.css('z-index', '8000001')
.appendTo('body');
$original = { top: e.pageY, left: e.pageX };
});
$feedbackOverlay.bind('mousemove', function (e)
{
var $currentHighlight = jQuery('#currentHighlight');
if ($currentHighlight.length > 0)
{
var $pos = { top: e.pageY, left: e.pageX };
if($pos.top < $original.top) $currentHighlight.css('top', $pos.top);
if ($pos.left < $original.left) $currentHighlight.css('left', $pos.left);
$currentHighlight.height(Math.abs($pos.top - $original.top));
$currentHighlight.width(Math.abs($pos.left - $original.left));
}
});
$feedbackOverlay.bind('mouseup', function (e)
{
var $currentHighlight = jQuery('#currentHighlight');
$currentHighlight.removeAttr('id');
});
var $feedbackInstructions = jQuery('#feedbackInstructions');
$feedbackInstructions.fadeIn(1000, function ()
{
setTimeout(function ()
{
$feedbackInstructions.fadeOut(1000);
}, 3000);
});
$feedbackOverlay.height(jQuery(document).height());
});
Here is a jsFiddle for the above:
http://jsfiddle.net/Chevex/RSYTq/
The problem is that I can't drag the boxes up or left. The first click puts the top left corner where the mouse clicked. After that subsequent dragging will change the width of the box. Letting go of the mouse completes the box and you may then start drawing another one. If you try to drag the DIV left or up while drawing it's width will remain at 0 but won't go negative.
Here you can find working solution: http://jsfiddle.net/RSYTq/34/
Something like this will get you closer to what you want: http://jsfiddle.net/RSYTq/18/
Doesn't quite handle move up and to the left and then switching to moving down and to the right quite right yet but it gives you the idea.
There's no such thing a a negative width - these are not coorindinates. You need to reposition and recalculate the corner positions relative to the corner that's not being moved.
Sounds like you need to check if the click origin (x,y) is > than the current mouse position, and then swap which one you use for the CSS top-left.
You would need to track the original start point somewhere (variables, data attributes on #currentHighlight, wherever you want), and check for width or height < 0. When so, set the #currentHighlight left/top CSS to be offset by original + (e.pageX - $currentHighlight.position().left) (for example). Then set the #currentHighlight width/height to the same difference (but positive: (e.pageX - $currentHighlight.position().left) * -1).

Categories