Link to home
Start Free TrialLog in
Avatar of JElster
JElsterFlag for United States of America

asked on

HTML - Canvas draw a gradient box

Hi..
I have code that places an X  (draws an X) based on x,y coordinates.  How can I do the same but fill the area with a gradient box instead.
Here's the 'X' code.
thx

   var ctx = canvas.getContext('2d');
          ctx.moveTo(x1, y1);
          ctx.lineTo(x2 + 1, y2 + 1);
          ctx.lineWidth = 4;
          ctx.strokeStyle = 'green';
          ctx.stroke();

          ctx.beginPath();
          ctx.moveTo(x2, y1);
          ctx.lineTo(x1 + 1, y2 + 1);
          ctx.lineWidth = 4;
          ctx.strokeStyle = 'red';
          ctx.stroke();
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Please try this:
          var ctx = canvas.getContext('2d');
          ctx.moveTo(x1, y1);
          ctx.lineTo(x2 + 1, y2 + 1);
          ctx.lineWidth = 4;
          //ctx.strokeStyle = 'green';
          var grd = ctx.createLinearGradient(x1, y1, x2, y2);
          grd.addColorStop(0, "#FF0000");
          grd.addColorStop(0.5, "#00FF00");
          grd.addColorStop(1, "#0000FF");
          ctx.strokeStyle = grd;
          ctx.stroke();

          ctx.beginPath();
          ctx.moveTo(x2, y1);
          ctx.lineTo(x1 + 1, y2 + 1);
          ctx.lineWidth = 4;
          //ctx.strokeStyle = 'red';
          var grd2 = ctx.createLinearGradient(x1, y2, x2, y1);
          grd2.addColorStop(0, "#FF0000");
          grd2.addColorStop(0.5, "#00FF00");
          grd2.addColorStop(1, "#0000FF");
          ctx.strokeStyle = grd2;
          ctx.stroke();

Open in new window

Avatar of JElster

ASKER

How can I fill in the whole area in gradient.
1 big gradient box.
thx!
You can use the gradient as strokeStyle or fillStyle just like using a color, for example:
          ctx.rect(0, 0, canvas.width, canvas.height);
          var grd = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
          grd.addColorStop(0, "#FF0000");
          grd.addColorStop(0.5, "#00FF00");
          grd.addColorStop(1, "#0000FF");
          ctx.fillStyle = grd;
          ctx.fill();

Open in new window

Avatar of JElster

ASKER

Sorry I mean the area of the X & Y
thx again
ASKER CERTIFIED SOLUTION
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of JElster

ASKER

thx again!