Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I interpolate between 2 points when drawing with canvas?

I have a paint-style application that works with touch events.

example

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.

like image 895
alex Avatar asked Dec 21 '22 04:12

alex


1 Answers

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}
like image 153
Ivan Kuckir Avatar answered Dec 29 '22 11:12

Ivan Kuckir