使用画布绘制时,如何在2个点之间进行插值?

时间:2013-06-19 12:19:10

标签: javascript canvas interpolation

我有一个适用于触摸事件的绘画风格的应用程序。

example

JavaScript代码是......

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

您可以使用Chrome并打开Web Inspector的设置并选择Emulate touch events,在不支持触摸事件的平台上对此进行测试。

当手指/指针移动得非常快时,它无法像预期的那样连续画出画布(见上面的截图)。似乎我只能在触发touchmove事件的同时获得触摸的坐标。

我认为我可以使用距离公式(c2 = a2 + b2)确定弧之间是否有足够大的间隙,并确定它是否大于RADIUS常数。这部分运作良好。我需要弄清楚的另一件事是如何在两点之间插值:先前注册的触摸坐标和新注册的坐标'。

所以,基本上,我想知道如何在两点之间进行插值,以确定如何填写差距。

1 个答案:

答案 0 :(得分:8)

您想要从最后一个鼠标位置到新鼠标位置绘制一条线。但是你正在新的位置画一个圆圈。为什么呢?

你为什么不这样做?

onTouchStart: ctx.moveTo(x,y);

onTouchMove: ctx.lineTo(x,y);

所有插值,抗锯齿等都已包含在“lineTo”功能中。使用ctx.lineCap = "round";有圆角。

如果您仍想插入数字,则可以使用以下函数:

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}
相关问题