【问题标题】:canvas ctx.stroke() no working/displaying properly (Javascript, Chrome)canvas ctx.stroke() 无法正常工作/显示(Javascript、Chrome)
【发布时间】:2017-08-23 22:40:08
【问题描述】:

我在画布上有网络摄像头流,但无法在顶部显示矩形。网络摄像头流有效。 问题是矩形没有出现,有时矩形会快速闪烁(而且也很模糊......)

网络摄像头到画布设置:

const canvas = document.querySelector('.photo');
const ctx = canvas.getContext('2d');

// gets the video stream from the user's webcam
function getVideo() {
 navigator.mediaDevices.getUserMedia({
  video: true,
  audio: false
}).then(localMediaStream => {
  video.src = window.URL.createObjectURL(localMediaStream);
  video.play();
}).catch(err => {
  console.error('oh no', err);
});
}

// Applies the webcam stream to a canvas
function paintToCanvas() {
 const width = video.videoWidth;
 const height = video.videoHeight;
 canvas.width = width;
 canvas.height = height;

 return setInterval(() => {
  ctx.drawImage(video, 0, 0, width, height);
 }, 16);
}

在顶部绘制矩形:

 function drawRectangle() {
  ctx.rect(150, 150, 50, 30);
  ctx.lineWidth = 2;
  ctx.strokeStyle = '#FF0000';
  ctx.stroke();
 }
 drawRectangle();

我尝试了不同的笔触、线宽和面积,但结果相同。 我究竟做错了什么?为什么它有时会闪烁(在页面加载时)而不是停留?

【问题讨论】:

    标签: javascript canvas webcam


    【解决方案1】:

    你需要使用 requestAnimationFrame 而不是 setInterval

    这样,当浏览器更新它的视口时,你的绘图就会发生。

    Drawing a shape in Canvas on repeat

     function draw() {
        requestAnimationFrame(draw);
        ctx.drawImage(video, 0, 0, width, height);
     }
    
    function paintToCanvas() {
     const width = video.videoWidth;
     const height = video.videoHeight;
     canvas.width = width;
     canvas.height = height;
     requestAnimationFrame(draw);
    }
    

    【讨论】:

    • 谢谢 Tschallacka,该链接可帮助我找到解决方法。
    • 当某个答案适合您时,您可以点击复选标记,向未来的访问者表明这是适合您的答案。
    【解决方案2】:

    这是我为修复它而添加的内容:

      let startTime;
      const interval=1;
    
      requestAnimationFrame(animate);
    
      function animate(t){
       requestAnimationFrame(animate);
       if(!startTime){startTime=t;}
       if(t-startTime<interval){return;}
       startTime=t;
       drawRectangle();
      }
    

    每毫秒(我的选择)绘制一次形状。测试和工作。 我停止在函数外部调用 drawRectangle,页面加载时也没有更多的 flash。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 2014-07-22
      • 2015-04-09
      • 1970-01-01
      • 2016-03-07
      相关资源
      最近更新 更多