使用javascript我在canvas元素上绘制一条'弯曲'路径,其中包含许多小直段:Harmonograph。
现在我想让每个片段都有不同的颜色,以便沿着路径应用彩虹色。 所以路径以红色开始,然后逐渐变为黄色,然后变为绿色等。
我只想使用beginPath()
和closePath()
一次来加快速度。
这是可能的,如createLinearGradient();
或任何其他标准函数,只要它很快,因为整个路径需要每秒重绘多次。
答案 0 :(得分:1)
除了分离路径之外,没有办法做到这一点。这是我为你的撒拉人形象实现的彩虹渐变。您可以看到演示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();
}
}
答案 1 :(得分:-1)
我有同样的问题,我做了一个简单的测试,这是工作 只需使用普通渐变,希望它有用
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();