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

折月煮酒 提交于 2019-12-12 09:52:12

问题


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.


回答1:


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}


来源:https://stackoverflow.com/questions/17190981/how-can-i-interpolate-between-2-points-when-drawing-with-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!