简体   繁体   中英

My Javascript gradient isn't working corectly

I am currently coding an interactive application using Javascript and the HTML canvas element. One of the things I'm coding is an opacity gradient. My gradient is supposed to fade from transparent to partially opaque, but the entire area I defined as the place to create the gradient is only partially opaque with no fade from transparency. Here's my code:

function draw() {

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var grd = ctx.createLinearGradient(0, 1000, 0, 0);

grd.addColorStop(0.5, "rgba(255, 255, 255, 0.5)");
grd.addColorStop(1, "rgba(255, 255, 255, 0)");
ctx.fillStyle = grd;
ctx.fillRect(0, 660, 1000, 10);

}

It has something to with the dimensions you use in createLinearGradient and fillRect . Right now you are defining your gradient area as a really tall thin rectangle [(0,0) to (0,1000)]. However, then you draw your gradient rectangle as a pretty big rectangle [(0,660) to (1000,10)].

I'm not exactly sure what your desired output looks like but it seems that your ctx.fillRect line is wrong. Trying the following works for me:

function draw() {

  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  var grd = ctx.createLinearGradient(0, 1000, 0, 0);

  grd.addColorStop(0.5, "rgba(255, 255, 255, 0.5)");
  grd.addColorStop(1, "rgba(255, 255, 255, 0)");
  ctx.fillStyle = grd;
  ctx.fillRect(0, 10, 1000, 660);

}

And the jsFiddle if you are interested

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM