Continuous gradient along a HTML5 canvas path

前端 未结 2 417
北海茫月
北海茫月 2020-12-19 19:01

I am trying to draw a continous gradient along a path of points, where each point has a it\'s own color, using the HTML5 canvas API.

See http://bl.ocks.org/rveciana/

2条回答
  •  忘掉有多难
    2020-12-19 19:16

    Here's a slight modification of your original idea that makes the joins blend nicely.

    enter image description here

    Original: Draw a gradient line from the start to end of a line segment.

    This causes the line joins to overlap and produces a noticeable & undesired transition.

    enter image description here

    Modification: Draw a gradient line that doesn't extend to the start / endpoints.

    With this modification, the line joins will always be solid colors rather than be partially gradiented. As a result, the line joins will transition nicely between line segments.

    enter image description here

    Here's example code and a Demo:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    
    var lines = [
      {x:100, y:050,color:'red'},
      {x:150, y:100,color:'green'},
      {x:200, y:050,color:'gold'},
      {x:275, y:150,color:'blue'}
    ];
    var linewidth=20;
    
    ctx.lineCap='round';
    ctx.lineJoint='round';
    
    for(var i=1;i
    #canvas{border:1px solid red; margin:0 auto; }

提交回复
热议问题