I have a paint-style application that works with touch events.
The JavaScript code is...
var RADIUS = 10;
var ctx = document.querySelector("canvas").getContext("2d");
var getRandomColorFragment = function () {
return Math.floor(Math.random() * 255);
};
document.body.addEventListener("touchstart", function (event) {
ctx.fillStyle = "rgb(" + [getRandomColorFragment(), getRandomColorFragment(), getRandomColorFragment()].join() + ")";
});
document.body.addEventListener("touchmove", function (event) {
// Prevent default behavior of scrolling elements.
event.preventDefault();
// Get a reference to the first touch placed.
var touch = event.touches[0];
// Draw a circle at the location of the finger.
ctx.beginPath();
ctx.arc(touch.pageX - RADIUS, touch.pageY - RADIUS, RADIUS, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
});
jsFiddle.
You can test this on a platform that doesn't support touch events by using Chrome and opening the Web Inspector's settings and choosing Emulate touch events.
When the finger/pointer moves very fast, it fails to paint the canvas continually like which would be expected (see screenshot above). It seems I can only get the touches' coordinates only as fast as the touchmove
event is triggered.
I thought that I could determine if there is a big enough gap between arcs using the Distance Formula (c2 = a2 + b2
) and determining if it's larger than the RADIUS
constant. This part worked well. The next thing I needed to figure out is how to interpolate between the two points: the previous registered touch's coordinates and the newly registered coordinates'.
So, essentially, I'd like to know how I could interpolate between the two points I have to determine how to fill-in the gap.
You want to draw a line from last mouse position to the new mouse postition. But you are drawing a circle at the new position instead. Why?
Why don't you do it this way?
onTouchStart: ctx.moveTo(x,y);
onTouchMove: ctx.lineTo(x,y);
All interpolation, antialiasing etc. is already included in "lineTo" function. Use ctx.lineCap = "round";
to have round corners.
If you still want to interpolate numbers, here is the function:
function interpolate(a, b, frac) // points A and B, frac between 0 and 1
{
var nx = a.x+(b.x-a.x)*frac;
var ny = a.y+(b.y-a.y)*frac;
return {x:nx, y:ny};
}
interpolate({x:2, y:2}, {x:4,y:4}, 0.5); // returns {x:3, y:3}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With