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

血红的双手。 提交于 2019-12-05 21:59:58
Ivan Kuckir

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