csscanvashtml5-canvashtml2canvas

calculated gradient in html2canvas doesn't work properly


I am trying to take a screenshot of a page that has images overlayed by linear-gradient with the help of html2canvas. The height of the image varies but the width is fixed to 210px so, i need to use calc to calculate the positons of the gradient, which is not rendering in the way it looks on the screen.

Example with static values: 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>

enter image description here

Example with calc values: 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>

enter image description here

Edit: Actual image overlayed on gradient looks like this:

enter image description here

The way it looks like in a screenshot is this:

enter image description here

The JS fiddle with my actual code is as follows (But the screenshot is a little different from my original one)

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


Solution

  • Here is a different idea to obtain the same gradient. There is a ton of ways but the below is the only one that worked with 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;
    }
    <div class="linearGradient"></div>

    Working code with html2canvas:

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