如何淡出html5画布中的元素

时间:2017-11-07 04:12:54

标签: javascript html5 canvas html5-canvas

我正在尝试通过编辑字符串rgba对Canvas中的矩形淡出淡出效果。我尝试减去并添加到不透明度值然后设置fillStyle函数,但到目前为止它似乎只是很快淡入淡出。任何帮助将不胜感激。

var ctx = cv.getContext('2d');
function fadeOutRectangle() {
var opacity = 1, 
  factor = 1,
  increment = .01;

  var steps = 50;
      ctx.fillStyle = 'rgba(0, 0, 0, ' + opacity + ')';
      ctx.fillRect(10, 10, 300, 300);

      interval = setInterval(function() {
          if(opacity >= 1) {
            factor = -1
          }
          else if(opacity <= 0) {
            factor = 1 ;
          }
          opacity += factor *increment;
          console.log("opacity",opacity);

          ctx.fillStyle = 'rgba(255, 255, 200, ' + opacity + ')';
          ctx.fillRect(20,20,150,100);

      }, 1000/steps);
    }
    fadeOutRectangle();

这也是jfiddle:

https://jsfiddle.net/dpxjfpgn/

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
var ctx = cv.getContext('2d');
var opacity = 1,
    factor = 1,
    increment = .01;

  var steps = 50, action = 'decrease';
function fadeOutRectangle() {
  var rectWidth = 300;
  var rectHeight = 300;

  interval = setInterval(function() {
    if (action == 'decrease') {
      rectWidth -= 1;
      if (rectWidth < 0) {
        action = 'increase'
      }
    } else {
      rectWidth += 1;
      if (rectWidth > 300) {
        action = 'decrease'
      }
    }
    if (opacity >= 1) {
      factor = -1
        // clearInterval(interval)
    } else if (opacity <= 0) {
      factor = 1;
    }
    opacity += factor * increment;

    // ctx.rect(20,20,150,100);
    //console.log(ctx.fillStyle)
    
    ctx.clearRect(0, 0, cv.width, cv.height);
    ctx.beginPath();
    ctx.fillStyle = 'rgba(0, 0, 0, 1)';
    ctx.fillRect(0, 0, 400, 400);
    ctx.fill();
    ctx.fillStyle = 'rgba(255, 255, 200, ' + opacity + ')';
    ctx.fillRect(20, 20, rectWidth, 100);
    //ctx.fill();

    // if(i === steps) {
    //     clearInterval(interval);
    // }
  }, 1000/steps);
  // clearInterval(interval)
}
fadeOutRectangle();
&#13;
<canvas width="400" height="400" id="cv"></canvas>
&#13;
&#13;
&#13;

使用clearRect()清除画布。然后重绘。 fadein增加矩形的宽度,淡出减小矩形的宽度。