echarts 图例legend添加渐变色背景 | canvas矩形圆角

需求:给echarts的每一项图例添加背景色。

echarts的API只支持配置全局的背景色,不能直接在legend中设置backgroundColor。

因此采取添加canvas再绘制的方式:

  const domMap = document.getElementById("pie");
  let parentDiv = domMap.firstChild; 
  // 创建canvas
  let canvas = document.createElement('canvas');
  canvas.width = parentDiv.offsetWidth;
  canvas.height =parentDiv.offsetHeight;
  parentDiv.appendChild(canvas);
  const context = canvas.getContext('2d'); 
  
  // 填充渐变颜色
  var gr = context.createLinearGradient(247, 63, 450, 0);
  // 颜色断点
  gr.addColorStop(1, 'rgba(15, 44, 79, 0.18)');
  gr.addColorStop(0, 'rgba(40, 72, 114, 0.91)');
  context.fillStyle = gr
 
  context.lineWidth = 1; // 设置线段宽度

  // 绘制圆角矩形
  drawRoundRect(context, 247, 63, 200, 24, 12)
  drawRoundRect(context, 247, 95, 200, 24, 12)
  drawRoundRect(context, 247, 127, 200, 24, 12)
  drawRoundRect(context, 247, 159, 200, 24, 12)
  drawRoundRect(context, 247, 191, 200, 24, 12)

  /* 不设置圆角的矩形绘制 */
  // context.beginPath(); // 开始点
  // context.fillRect(247, 63,200, 24)
  // context.fillRect(247, 95,200, 24)
  // context.fillRect(247, 127,200, 24)
  // context.fillRect(247, 159,200, 24)
  // context.fillRect(247, 191,200, 24)

绘制圆角矩形的方法:

const drawRoundRect = ( ctx, x, y, width, height, radius ) => {   
  // ctx, 矩形距离x坐标位置, 矩形距离y坐标的位置, 矩形的宽, 矩形的长,圆角角度 
	ctx.beginPath();    
	ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2);    
	ctx.lineTo(width - radius + x, y);    
	ctx.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2);    
	ctx.lineTo(width + x, height + y - radius);    
	ctx.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2);    
	ctx.lineTo(radius + x, height +y);    
	ctx.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI);    
	ctx.closePath();    
  ctx.stroke();
  ctx.fill()
}

效果:

 

 知识点

  • createLinearGradient() 方法:

        创建线性的渐变对象,渐变可用于填充矩形、圆形、线条、文本等等。

参数描述
x0渐变开始点的 x 坐标
y0渐变开始点的 y 坐标
x1渐变结束点的 x 坐标
y1渐变结束点的 y 坐标
  • fillRect(x,y,width,height) 方法绘制"已填充"的矩形。默认的填充颜色是黑色。

    提示:请使用 fillStyle 属性来设置用于填充绘图的颜色、渐变或模式。

    参数描述
    x矩形左上角的 x 坐标。
    y矩形左上角的 y 坐标。
    width矩形的宽度,以像素计。
    height矩形的高度,以像素计。
  • stroke() 方法会实际地绘制出通过 moveTo() 和 lineTo() 方法定义的路径。默认颜色是黑色。

    提示:请使用 strokeStyle 属性来绘制另一种颜色/渐变。

  • fill() 方法填充当前的图像(路径)。默认颜色是黑色。

    提示:请使用 fillStyle 属性来填充另一种颜色/渐变。

    注意:如果路径未关闭,那么 fill() 方法会从路径结束点到开始点之间添加一条线,以关闭该路径(正如 closePath() 一样),然后填充该路径。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值