【问题标题】:The compliance properties of the elements of the array by i数组元素的依从性属性 i
【发布时间】:2018-08-11 15:41:46
【问题描述】:

在画布上,我分配了一组带有坐标的星星:

x: randomInt(1, canvas.width - 1),
y: randomInt(0, canvas.height - 1),

每个星星的初始不透明度 (op) 值为 1。在动画期间,不透明度变为 0(星星消失)。

应该是画布顶部的星星 (y < 75) 的消失速度与底部的星星不同,因为下面的代码设置了每一帧的不透明度值:

 for (let i = 0; i < SF_COUNT; i++) {
     if (stars[i].y < 75) {stars[i].op -= 0.001;}    
     else {stars[i].op -= 0.01;}
 }

然而,实际发生的是星星确实以不同的速率进行动画处理,但这种差异出现随机(即不限于画布顶部的星星) .为什么? http://jsfiddle.net/Nata_Hamster/6jdnq3ry/

【问题讨论】:

  • 抱歉,我听不懂您使用的语言。你能说得清楚点吗?
  • @connexo,谢谢))我正在努力提高我的英语)我希望,此时清楚。

标签: javascript arrays canvas


【解决方案1】:

您将 strokeStyle 作为最后一步,而它应该是第一步......

这是您的代码,经过我的更正:
还添加了一些其他小的改进,使代码更具可读性

var canvas = document.getElementById("drawingCanvas");
var context = canvas.getContext("2d");
var stars = [];

const SF_COUNT = 500;
context.lineWidth = 1.1;

window.onload = function() {
  changeColor1();
  drawFrame();
}

for (let i = 0; i < SF_COUNT; i++) {
  stars.push({
    x: randomInt(1, canvas.width - 1),
    y: randomInt(0, canvas.height - 1),
    op: 1
  });
}

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min));
}

function snowflake(star) {
  context.strokeStyle = 'rgba(255,255,255,' + star.op + ')';
  context.beginPath();
  context.moveTo(star.x, star.y);
  context.lineTo(star.x + context.lineWidth, star.y + context.lineWidth);
  context.stroke();
}

function drawFrame() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  for (let i = 0; i < SF_COUNT; i++)
    snowflake(stars[i]);
  setTimeout(drawFrame, 190);
}

function changeColor1() {
  for (let i = 0; i < SF_COUNT; i++)
    if (stars[i].op > 0)
      stars[i].op -= (stars[i].y < 75) ? 0.002 : 0.01;
  requestAnimationFrame(changeColor1);
}
#drawingCanvas {
  height: 170px;
  width: 400px;
  background-color: #000;
}
&lt;canvas id="drawingCanvas"&gt;&lt;/canvas&gt;

【讨论】:

  • 很好看!我也试图解决这个问题,但无法解决(我想缺乏画布经验)。我是否正确理解发生的事情是因为笔触样式仍然存在,所以每颗星星(或雪花)都被分配了前一颗星星的不透明度?
  • @DesperateEi 是的,标题很误导
【解决方案2】:

错误:

现在您的drawFrame 代码在 绘制星形之后设置不透明度,这意味着不透明度会影响下一个 星而不是当前星:

...
// draw all SF_COUNT stars
for (let i = 0; i < SF_COUNT; i++) {
    // this draws star i with the *current* context.strokeStyle
    snowflake(stars[i].x, stars[i].y);
    // this sets the context.strokeStyle for star i + 1
    context.strokeStyle = 'rgba(255,255,255,' + stars[i].op + ')';
}
...

修复:

交换两条线,以便在绘制星星之前设置颜色:

...
// draw all SF_COUNT stars
for (let i = 0; i < SF_COUNT; i++) {   
    // this sets the context.strokeStyle, changing the opacity of star i
    context.strokeStyle = 'rgba(255,255,255,' + stars[i].op + ')';
    // this draws star i with the new context.strokeStyle
    snowflake(stars[i].x, stars[i].y);
}
...

Here's a fixed codepen.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2022-12-31
    • 1970-01-01
    • 2020-08-06
    • 2012-03-15
    • 1970-01-01
    相关资源
    最近更新 更多