问题
So I want to measure how fast and what direction a user swipes on an html5 canvas?
Seems like there should be something already written to do this so I dont have to re-invent the wheel, but I cant find anything. Anyone know of a JavaScript function?
If I had to do myself, I am thinking this:
- grab the touch events x & y, store them in an array variable
- calculate slope between 2 points (maybe average it out if the slopes are different)
- not sure how to measure velocity, maybe the distance between points?
any other ideas?
Here is my canvas and my shape, and it listens on touch events. When touch on my iphone or iphone simulator I usually get 1 or 2 events. I see the coordinates. I am using kineticjs for the stage and shape.
To try it, go to this url in your iphone and put your finger on the circle and push it somewhere. (or if you have ios simulator you can use that also)
Here is my fiddle: http://jsfiddle.net/jnylund/uRgZZ/16/
function writeMessage(messageLayer, message) {
var context = messageLayer.getContext();
messageLayer.clear();
context.font = '18pt Calibri';
context.fillStyle = 'black';
context.fillText(message, 10, 25);
var div = document.getElementById('tevents');
div.innerHTML = div.innerHTML + message + "<BR/>";
}
var stage = new Kinetic.Stage({
container: 'container',
width: 460,
height: 320
});
var layer = new Kinetic.Layer();
var messageLayer = new Kinetic.Layer();
var circle = new Kinetic.Circle({
x: stage.getWidth() / 2,
y: stage.getHeight() / 2,
radius: 40,
fill: 'red',
stroke: 'black',
strokeWidth: 4 //,
// draggable: true
});
circle.setX(230);
circle.setY(160);
circle.on('touchmove', function (event) {
writeMessage(messageLayer, 'touch event length is ' + event.touches.length);
for (var i = 0; i < event.touches.length; i++) {
var touch = event.touches[i];
writeMessage(messageLayer, 'event x: ' + touch.pageX + ', y: ' + touch.pageX);
}
var touchPos = stage.getTouchPosition();
writeMessage(messageLayer, 'stage x: ' + touchPos.x + ', y: ' + touchPos.y);
});
// add the shape to the layer
layer.add(circle);
// add the layer to the stage
stage.add(layer);
stage.add(messageLayer);
thanks Joel
回答1:
You can do it simply with these steps:
- Touch down, store time and position
- Touch up, store time and position
In the same handler as touch up continue with these steps:
- Subtract start time from end time
- Calculate distance between start point and end point
- Calculate angle between start point and end point
To get a factor to relate to you divide distance on time difference. The higher value the faster the velocity.
回答2:
Velocity can be measured a number of ways:
- Timestamps between your initial and final points measured in pixels per millisecond.
- Framerate, for fixed rates, measured in pixels per frame or pixels per second.
Then convert the values to the scale used in your app, like kph or mph for racing.
来源:https://stackoverflow.com/questions/16091701/html5-canvas-touchmove-how-to-calculate-velocity-and-direction