gpt4 book ai didi

javascript - 沿 HTML5 Canvas 路径的连续渐变

转载 作者:搜寻专家 更新时间:2023-10-31 22:06:03 24 4
gpt4 key购买 nike

我正在尝试使用 HTML5 canvas API 沿着点路径绘制连续渐变,其中每个点都有自己的颜色。

参见 http://bl.ocks.org/rveciana/10743959为了获得灵感,D3 实现了这种效果。

似乎没有办法为单个 Canvas 路径添加多个线性渐变,所以我求助于这样的方法:http://jsfiddle.net/51toapv2/

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

var pts = [[100, 100, "red"], [150, 150, "green"], [200, 100, "yellow"]];

ctx.lineWidth = 20;
ctx.lineJoin = "round";
ctx.lineCap = "round";

for (var i = 0; i < pts.length - 1; i++) {
var begin = pts[i];
var end = pts[i + 1];

ctx.beginPath();
var grad = ctx.createLinearGradient(begin[0], begin[1], end[0], end[1]);
grad.addColorStop(0, begin[2]);
grad.addColorStop(1, end[2]);
ctx.strokeStyle = grad;
ctx.moveTo(begin[0], begin[1]);
ctx.lineTo(end[0], end[1]);
ctx.stroke();
}

如您所见,由于路径未合并且“线连接”清晰可见,因此效果不佳。

是否可以使用 canvas API 实现我正在寻找的效果?

最佳答案

这里对您的原始想法稍作修改,使连接很好地融合在一起。

enter image description here

原文:从线段的起点到终点画一条渐变线。

这会导致连接线重叠并产生明显且不希望出现的过渡。

enter image description here

修改:画一条不延伸到起点/终点的渐变线。

通过此修改,连接线将始终为纯色,而不是部分渐变。因此,线连接将在线段之间很好地过渡。

enter image description here

这是示例代码和演示:

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<lines.length;i++){

// calculate the smaller part of the line segment over
// which the gradient will run
var p0=lines[i-1];
var p1=lines[i];
var dx=p1.x-p0.x;
var dy=p1.y-p0.y;
var angle=Math.atan2(dy,dx);
var p0x=p0.x+linewidth*Math.cos(angle);
var p0y=p0.y+linewidth*Math.sin(angle);
var p1x=p1.x+linewidth*Math.cos(angle+Math.PI);
var p1y=p1.y+linewidth*Math.sin(angle+Math.PI);

// determine where the gradient starts and ends
if(i==1){
var g=ctx.createLinearGradient(p0.x,p0.y,p1x,p1y);
}else if(i==lines.length-1){
var g=ctx.createLinearGradient(p0x,p0y,p1.x,p1.y);
}else{
var g=ctx.createLinearGradient(p0x,p0y,p1x,p1y);
}

// add the gradient color stops
// and draw the gradient line from p0 to p1
g.addColorStop(0,p0.color);
g.addColorStop(1,p1.color);
ctx.beginPath();
ctx.moveTo(p0.x,p0.y);
ctx.lineTo(p1.x,p1.y);
ctx.strokeStyle=g;
ctx.lineWidth=linewidth;
ctx.stroke();
}
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=350 height=200></canvas>

关于javascript - 沿 HTML5 Canvas 路径的连续渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30631032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com