代码之家  ›  专栏  ›  技术社区  ›  fightstarr20

getusermedia-镜像而不是翻转

  •  0
  • fightstarr20  · 技术社区  · 7 年前

    我正在使用getusermedia从视频流中获取图像并像这样镜像它…

    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    
    var ctx = canvas.getContext('2d');
    ctx.setTransform(1,0,0,-1,0,canvas.height)
    
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    
    dataUrl = canvas.toDataURL('image/jpeg');
    

    但它并没有模仿它,而是把它颠倒过来。我哪里做错了?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Kaiido NickSlash    7 年前

    canvascontext2d.settransform的参数是

    setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY)
    

    你在设置 scaleY 到-1并在y轴上按高度平移。实际上,你是垂直翻转的。

    要水平翻转

    ctx.setTransform(-1,0,0,1,canvas.width,0);
    

    const vid = document.createElement('video');
    const ctx = canvas.getContext('2d');
    // gUM has problems with StackSnippet's overprotected iframes
    // so we'll use a normal video instead
    vid.src = 'https://upload.wikimedia.org/wikipedia/commons/transcoded/a/a4/BBH_gravitational_lensing_of_gw150914.webm/BBH_gravitational_lensing_of_gw150914.webm.480p.webm';
    vid.play()
      .then(() => {
        canvas.width = vid.videoWidth;
        canvas.height = vid.videoHeight;
        drawloop();
      });
    
    function drawloop() {
      if (inp.checked) {
        ctx.setTransform(-1, 0, 0, 1, canvas.width, 0);
      } else {
        ctx.setTransform(1, 0, 0, 1, 0, 0);
      }
      ctx.drawImage(vid, 0, 0);
      requestAnimationFrame(drawloop);
    }
    canvas {
      width: 100%;
    }
    <label>flip horizontally<input type="checkbox" id="inp"></label><br>
    <canvas id="canvas"></canvas>