javascript - 如何淡入html5 Canvas 中的元素

标签 javascript html 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/

最佳答案

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();
<canvas width="400" height="400" id="cv"></canvas>

使用 clearRect() 清除 Canvas 。然后重画。淡入时增加矩形的宽度,淡出时减少矩形的宽度。

关于javascript - 如何淡入html5 Canvas 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47149853/

相关文章:

javascript - 有什么办法可以禁用所有 firebase 日志记录到控制台吗?

javascript - 为什么 !在函数不返回相反的 bool 值之前?

javascript - 将多维数组中的 HTML 表格与数据驱动文档分组

html - 文本框中带有按钮的搜索框

javascript - HTML5 canvas 绘制多个在 Canvas 中移动的矩形

php - 无法将大型 html5 Canvas 发布到服务器?

javascript - HTML5 语音合成在阅读时缺少一些文本

html - 同名表单字段上的 css

html - 修复右侧下拉菜单和导航菜单

android - 刷新 SurfaceView-->OnClickListener Android 上的 Canvas