6

How can I draw a rectangle with a gradient effect like the one pictured below using the HTML5 canvas element?

sample

Edit: Thanks for all the feedback. Yes, I have already tried many methods. For example, can I use the createRadialGradient method as @Loktar suggests? Here is some sample code:

<html>
  <head>
    <title>test</title>
      <script type="application/x-javascript">
        function draw() {
          var canvas = document.getElementById("canvas"),
          ctx = canvas.getContext("2d");

          var grad1 = ctx.createRadialGradient(50, 50, 0, 50, 50, 50);
          grad1.addColorStop(0, 'rgba(255, 252, 0, 1)');
          grad1.addColorStop(1, 'rgba(68, 205, 37, 1)');

          ctx.fillStyle = grad1;
          ctx.fillRect(0, 0, 100, 100);
       }
    </script>
  </head>
  <body onload="draw();">
    <div>
      <canvas id="canvas" width="100" height="100"></canvas>
    </div>
  </body>
</html>

But the result is not quite what I want:

result

This should be done easily with a method like PathGradientBrush provided by GDI+. I'm not sure is it possible with the HTML5 canvas element.

3
  • 2
    What have you tried so far? p.s. developer.mozilla.org/en/… 5 mins and u'll be able to do it!
    – stecb
    Aug 11, 2011 at 19:01
  • 1
    heh idk about 5 mins. Heres my horrid attempt, not even going to post it as answer jsfiddle.net/loktar/MAjPQ/1
    – Loktar
    Aug 11, 2011 at 20:24
  • obv '5 mins' means it's easy to read that doc and try to get a solution easily :)
    – stecb
    Aug 12, 2011 at 7:33

1 Answer 1

5

You could try to use a combination of linear gradient and clipping. Demo. Code:

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

var outerColor = 'rgba(68,205,37,1)';
var innerColor = 'rgba(255,252,0,1)';

var w = 200;
var h = 50;
canvas.width = w;
canvas.height = h;

function gradient(dir) {
    var grad = ctx.createLinearGradient(dir[0], dir[1], dir[2], dir[3]);

    grad.addColorStop(0, outerColor);
    grad.addColorStop(0.5, innerColor);
    grad.addColorStop(1.0, outerColor);

    return grad;
}

// idea: render background gradient and a clipped "bow"
function background() {
    ctx.fillStyle = gradient([0, 0, 0, h]);
    ctx.fillRect(0, 0, w, h);
}

function bow() {
    ctx.save();

    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(w, h);
    ctx.lineTo(w, 0);
    ctx.lineTo(0, h);
    ctx.clip();

    ctx.fillStyle = gradient([0, 0, w, 0]);
    ctx.fillRect(0, 0, w, h);

    ctx.restore();
}

background();
bow();
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.