【问题标题】:How can I draw a curved path with a gradient on the html5 canvas?如何在 html5 画布上绘制带有渐变的曲线路径?
【发布时间】:2013-01-01 23:19:50
【问题描述】:

使用 javascript,我在 canvas 元素上绘制了一条“弯曲”路径,该路径由许多小的直线段组成:Harmonograph

现在我希望每个路段都具有不同的颜色,以便沿路径应用彩虹色。 所以路径从红色开始,然后逐渐变为黄色,然后变为绿色,等等。

我只想使用一次beginPath()closePath() 来加快速度。 这是否可以通过 createLinearGradient(); 之类的函数或任何其他标准函数实现,只要速度快,因为整个路径需要每秒重绘多次。

【问题讨论】:

  • 请贴出您当前使用的代码。
  • @Asad,粘贴代码似乎不起作用...但我想你已经找到了我正在使用的代码here

标签: javascript canvas gradient


【解决方案1】:

除了分隔路径之外,没有其他方法可以做到这一点。这是我为您的 lissajous 人物实现的彩虹渐变。可以看演示here

drawLissajous: function(points) {
    if (points.length > 2) {
        var x, y, x = points[1][0] + this.centerX;
        y = points[1][1] + this.centerY;
        ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.beginPath();
        ctx.moveTo(x, y);
        for (var count = 2; count < points.length; count++) {
            ctx.beginPath();
            ctx.moveTo(x, y);
            var newX = points[count][0] + this.centerX,
                newY = points[count][1] + this.centerY,
                f = 0.005,
                blue = Math.sin(f * count + 0) * 127 + 128,
                red = Math.sin(f * count + 2) * 127 + 128,
                green = Math.sin(f * count + 4) * 127 + 128;
            ctx.strokeStyle = 'rgb(' + Math.round(red) + ', ' + Math.round(green) + ', ' + Math.round(blue) + ')';
            x = newX;
            y = newY;
            ctx.lineTo(x, y);
            ctx.stroke();
            ctx.closePath();
        }
        ctx.stroke();
        ctx.closePath();
    }
}

【讨论】:

  • 非常感谢,这就是我要找的。令我惊讶的是,速度仍然很高。穿越彩虹色的好方法!
  • @Esger 没问题。您还可以尝试使用正弦函数:例如,您可以通过给每个波一个单独的频率来调整模式。或者,您可以通过减少最后添加的常量来减少图案的红色。
【解决方案2】:

我有同样的问题,我做了一个简单的测试,它是工作 只是使用普通渐变,希望它有用

 var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    context.beginPath();
    context.moveTo(100, 20);

    // line 1
    context.lineTo(200, 160);

    // quadratic curve
    context.quadraticCurveTo(230, 200, 250, 120);

    // bezier curve
    context.bezierCurveTo(290, -40, 300, 200, 400, 150);

    // line 2
    context.lineTo(500, 90);

    // create radial gradient
    var grd = context.createRadialGradient(238, 50, 10, 238, 50, 300);
    // light blue
    grd.addColorStop(0, '#8ED6FF');
    // dark blue
    grd.addColorStop(1, '#004CB3');

    context.lineWidth = 5;
    context.strokeStyle = grd;
    context.stroke();

here test

【讨论】:

  • 这是错误的。您正在创建叠加在线的径向渐变,而不是沿线的渐变。
猜你喜欢
  • 1970-01-01
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 2014-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多