【问题标题】:calculated gradient in html2canvas doesn't work properlyhtml2canvas 中的计算梯度无法正常工作
【发布时间】:2020-10-08 02:44:30
【问题描述】:

我正在尝试在 html2canvas 的帮助下截取具有由线性渐变覆盖的图像的页面的屏幕截图。图像的高度不同,但宽度固定为 210 像素,所以我需要使用 calc 来计算渐变的位置,而不是按照它在屏幕上显示的方式渲染。

静态值示例:https://jsfiddle.net/vpj3bz7s/1/

.linearGradient {
  height: 200px;
  width: 210px;
  background-image: linear-gradient(to top left,
      yellow 0%,
      yellow 80px,
      red 80px,
      red 110px,
      yellow 110px,
      yellow 100%);
}
html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
  }
);
<div class="linearGradient"></div>

计算值示例:https://jsfiddle.net/dk309pf6/2/

.linearGradient {
  height: 200px;
  width: 210px;
  background-image: linear-gradient(to top left,
      yellow 0%,
      yellow calc(50% - 10px),
      red calc(50% - 10px),
      red calc(50% + 10px),
      yellow calc(50% + 10px),
      yellow 100%);
}

html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
  }
);
<div class="linearGradient"></div>

编辑: 叠加在渐变上的实际图像如下所示:

它在屏幕截图中的样子是这样的:

我的实际代码的JS小提琴如下(但截图和我原来的有点不同)

https://jsfiddle.net/nrfjh8m3/1/

【问题讨论】:

  • 该错误已报告:github.com/niklasvh/html2canvas/issues/1989 对于可能的解决方法,您可以在页面中更改什么?
  • 谢谢。我尝试使用这个线性渐变来解决它(左上角,透明 0%,透明 47%,红色 47%,红色 52%,透明 52%,透明 100%)

标签: css canvas html5-canvas html2canvas


【解决方案1】:

这是获得相同梯度的不同想法。有很多方法,但以下是唯一一种与 html2canvas 一起使用的方法:

body {
  margin: 0px;
}

.linearGradient {
  height: 200px;
  width: 210px;
  background-color:red;
  overflow:hidden;
   position:relative;
}
.linearGradient::before,
.linearGradient::after {
   content:"";
   position:absolute;
   top:0;
   left:0;
   bottom:0;
   right:0;
   background-repeat:no-repeat;
}
.linearGradient::before {
  background:linear-gradient(to bottom right,yellow 49%, transparent 50%);
  bottom:10px;
  right:10px;
}
.linearGradient::after {
  background:linear-gradient(to top left,yellow 49%, transparent 50%);
  top:10px;
  left:10px;
}
&lt;div class="linearGradient"&gt;&lt;/div&gt;

使用 html2canvas 的工作代码:

https://jsfiddle.net/k79ybnup/1/

【讨论】:

  • 我觉得你的回答很好,但在我的实际情况下,我使用透明背景代替黄色,我附上了截图,我将很快添加jsfiddle,如何在那些场景中完成
  • 我能够使用线性渐变实现它(左上角,透明 0%,透明 47%,红色 47%,红色 52%,透明 52%,透明 100%)
  • @Rax 是的,我也在考虑那个,但我认为您需要精确的值,这就是您使用 calc 的原因
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多