简体   繁体   English

我的Javascript渐变无法正常工作

[英]My Javascript gradient isn't working corectly

I am currently coding an interactive application using Javascript and the HTML canvas element. 我目前正在使用Javascript和HTML canvas元素编写一个交互式应用程序。 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 . 它与您在createLinearGradientfillRect使用的尺寸有关。 Right now you are defining your gradient area as a really tall thin rectangle [(0,0) to (0,1000)]. 现在,您将渐变区域定义为一个非常高的细矩形[(0,0)到(0,1000)]。 However, then you draw your gradient rectangle as a pretty big rectangle [(0,660) to (1000,10)]. 但是,然后将渐变矩形绘制为相当大的矩形[(0,660)至(1000,10)]。

I'm not exactly sure what your desired output looks like but it seems that your ctx.fillRect line is wrong. 我不确定您想要的输出是什么样子,但是您的ctx.fillRect行似乎是错误的。 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 还有jsFiddle如果您有兴趣

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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