繁体   English   中英

如何淡出html5 canvas中的元素

[英]How to fade in out an element in 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()清除画布。 然后重画。 淡入增加矩形的宽度,淡出减小矩形的宽度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM