how to draw smooth curve through N points using javascript HTML5 canvas?

后端 未结 11 572
时光说笑
时光说笑 2020-11-22 16:40

For a drawing application, I\'m saving the mouse movement coordinates to an array then drawing them with lineTo. The resulting line is not smooth. How can I produce a sing

11条回答
  •  死守一世寂寞
    2020-11-22 17:29

    Incredibly late but inspired by Homan's brilliantly simple answer, allow me to post a more general solution (general in the sense that Homan's solution crashes on arrays of points with less than 3 vertices):

    function smooth(ctx, points)
    {
        if(points == undefined || points.length == 0)
        {
            return true;
        }
        if(points.length == 1)
        {
            ctx.moveTo(points[0].x, points[0].y);
            ctx.lineTo(points[0].x, points[0].y);
            return true;
        }
        if(points.length == 2)
        {
            ctx.moveTo(points[0].x, points[0].y);
            ctx.lineTo(points[1].x, points[1].y);
            return true;
        }
        ctx.moveTo(points[0].x, points[0].y);
        for (var i = 1; i < points.length - 2; i ++)
        {
            var xc = (points[i].x + points[i + 1].x) / 2;
            var yc = (points[i].y + points[i + 1].y) / 2;
            ctx.quadraticCurveTo(points[i].x, points[i].y, xc, yc);
        }
        ctx.quadraticCurveTo(points[i].x, points[i].y, points[i+1].x, points[i+1].y);
    }
    

提交回复
热议问题