getusermedia - 镜像而不是翻转

时间:2018-06-04 13:17:53

标签: html css getusermedia drawimage

我正在使用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 个答案:

答案 0 :(得分:1)

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>

相关问题