Skip to content
Advertisement

CSS convert gradient to the canvas version

I have a gradient that I need to apply to a canvas.

section {
  width: 440px;
  height: 171px;
  background-image: linear-gradient(185deg, #39adb2 0%, rgba(255, 255, 255, 0.24) 100%), linear-gradient(to top, rgba(152, 227, 230, 0.18) 0%, rgba(196, 229, 255, 0) 99%, rgba(196, 229, 255, 0) 100%);
  opacity: 0.48;
}
<section></section>

I need help to convert this to the canvas API; I don’t have a clue how to do it. maybe there is an online tool?

  var gradientFill = ctx.createLinearGradient(100, 10, 100, 100);
  gradientFill.addColorStop(0, "#39adb2");
  gradientFill.addColorStop(0.99, "rgba(196, 229, 255, 0)");
  gradientFill.addColorStop(1, "rgba(196, 229, 255, 0)");
  gradientFill.addColorStop(0, "#39adb2");
  gradientFill.addColorStop(1, "rgba(152, 227, 230, 0.18)");

Advertisement

Answer

Here is how you can convert the CSS gradient to canvas version …

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

var grd = ctx.createLinearGradient(0, 0, 0, 171);
grd.addColorStop(0,"#39ADB2");
grd.addColorStop(0,"#98E3E6");
grd.addColorStop(1,"#FFFFFF");

ctx.fillStyle = grd;
ctx.fillRect(0, 0, canvas.width, canvas.height);
<canvas id="canvas" width="440" height="171"></canvas>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement