javascript - 我无法让连续的 Canvas 矩形在 js 中具有重复的线性渐变。任何人都知道如何?

标签 javascript html5-canvas linear-gradients

我绘制了一个带有连续矩形的 Canvas ,每个矩形都有自己的线性渐变,但我无法让线性渐变显示在矩形上,除了第一个矩形。每个矩形大小相同,每个矩形都应具有相同的线性渐变。我只能使第一个矩形具有正确的渐变,但其余的都没有。其余为黑色。一直在寻找整个互联网,找不到答案。我哪里做错了?谢谢!

这是一支写有我的代码的笔:https://codepen.io/monamoves/pen/RQvzOe

又来了。

HTML:

<canvas id="fabric" width="1020" height="300">
</canvas>

CSS:

canvas {
  border: thin red solid;
}

JavaScript:

window.onload = draw;

function draw() {
var cvs = document.getElementById("fabric");
var ctx = cvs.getContext("2d");

var xcoordinate = 0;
var grd = ctx.createLinearGradient(xcoordinate, 0, xcoordinate + 20, 0);

for (var i = 0; i < 50; i++) {
  ctx.beginPath();
  ctx.strokeStyle="#ccc";
  ctx.moveTo(xcoordinate, 0);
  ctx.rect(xcoordinate, 0, 20, 300);
  ctx.stroke();
  ctx.fillStyle = grd;
  grd.addColorStop(0, "black");
  grd.addColorStop(0.5, "white");
  grd.addColorStop(1, "black");
  ctx.fill();
  xcoordinate = xcoordinate + 20;  
}
}

最佳答案

您将渐变定义为仅在第一个矩形上方。渐变不遵循您的形状,如果您告诉它在坐标 0,0 处的宽度为 20 像素,则在这些坐标之外绘制的每个形状都将是您设置的 2 种极端颜色之一。

您可以在 for 循环内的每次迭代中创建一个新的渐变,实际上,如果您想要更改其 colorStops,则必须这样做。

但在你的情况下(单一渐变)最好的解决方案是只声明一次你的渐变,只设置一次它的 colorStops,并简单地修改你的上下文的转换矩阵;梯度也会受到影响。

var ctx = cvs.getContext("2d");

var xcoordinate = 0;
// set all this only once if it doesn't change
var grd = ctx.createLinearGradient(0, 0, 20, 0);
ctx.fillStyle = grd;
grd.addColorStop(0, "black");
grd.addColorStop(0.5, "white");
grd.addColorStop(1, "black");
ctx.strokeStyle="#ccc";

for (var i = 0; i < 50; i++) {
  ctx.beginPath();
  // we move the transform matrix
  ctx.setTransform(1,0,0,1,xcoordinate,0);
  // and draw always at same coords
  ctx.moveTo(0, 0);
  ctx.rect(0, 0, 20, 300);
  ctx.stroke();
  ctx.fill();
  xcoordinate = xcoordinate + 20;  
}
<canvas id=cvs></canvas>

关于javascript - 我无法让连续的 Canvas 矩形在 js 中具有重复的线性渐变。任何人都知道如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49079286/

相关文章:

javascript - 带有 n3 图表的 AngularJS D3 可视化

javascript - jquery slideDown() 覆盖最后一个元素

javascript - HTML5 canvas 绘制带有内嵌边框的图像

javascript - CreateJS 对象可见性

html - 导航栏按具有线性渐变的颜色/图像水平分割

ios - 当与背景属性中的图像 url 结合时,CSS 线性渐变在 iOS 上不起作用

javascript - 如何在 IE8 及更早版本中使用 JavaScript 设置光标位置?

javascript - Bootstrap 3 具有显示和隐藏事件的嵌套可折叠元素

javascript - HTML5 删除 Canvas 中先前绘制的对象

JQuery:设置 CSS 渐变不起作用