单击按钮后淡出 canvas 中的每个框(动画)

Fadeout each of the box in canvas after button click (animate)

嗨,我是 canvas/jquery 的新手,我想在单击按钮后淡出每个框。但目前我所做的是单击按钮后整个 canvas 淡出。请问有什么方法可以使 canvas 中的每个框淡出吗?谢谢

代码如下:

<!DOCTYPE html>
<html>

<head>
    <title>Page Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>

<body style="background: black;">
    <canvas id="NodeList" width="400" height="100"></canvas>
    <button id="k">Hello</button>
</body>

</html>

您可以使用 clearRectsetTimeout 来实现。

演示代码 :

var data = [{
    "name": "1",
    "x": 20,
    "y": 21,
    "width": 80,
    "height": 80,
    "bgColor": "#00FF00",
    "radius": 2,
    "version": "1.0.0"
  }
  // for horizontal
  , {
    "name": "5",
    "x": 110,
    "y": 21,
    "width": 80,
    "height": 80,
    "bgColor": "#00FF00",
    "radius": 2
  }, {
    "name": "6",
    "x": 200,
    "y": 21,
    "width": 80,
    "height": 80,
    "bgColor": "#00FF00",
    "radius": 2
  }, {
    "name": "5",
    "x": 290,
    "y": 21,
    "width": 80,
    "height": 80,
    "bgColor": "#00FF00",
    "radius": 2
  }
  // end horizontal

];
var c = document.getElementById("NodeList");
var ctx = c.getContext("2d");

ctx.strokeStyle = "black";
for (let i = 0; i < data.length; i++) { // loop through the data array
  const _data = data[i];
  ctx.beginPath(); // Call beginPath before drawing any shape
  ctx.fillStyle = "white";
  ctx.fillRect(_data.x, _data.y, _data.width, _data.height);
  ctx.fillStyle = "black";
  ctx.fillText(_data.name, _data.x + 10, _data.y + 20); // +10 means the offset
  ctx.stroke();
}
$("#k").click(function() {
  for (let i = 0; i < data.length; i++) {
    const _data = data[i];
    //clear one by one
    setTimeout(function() {
      ctx.clearRect(_data.x, _data.y, _data.width, _data.height);
    }, 1000 * i);
  }
  
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body style="background: black;">
    <canvas id="NodeList" width="400" height="100"></canvas>
    <button id="k">Hello</button>
</body>