画在画布上与图像

问题描述 投票:0回答:1

我有一个播放mp4视频的视频元素。单击屏幕截图按钮时,它会在画布上绘制当前视频帧。然后我想画在画布上。

我的问题是我无法使光标与绘图坐标对齐。我怀疑这是因为我设置画布的高度和宽度以便能够正确地绘制视频帧。

最小的repro:https://codepen.io/stiba/pen/KEBRdy

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var video = document.getElementById('vid');
canvas.addEventListener('mousedown', mouseDown);
canvas.addEventListener('mouseup', mouseUp);
canvas.addEventListener('mousemove', mouseMove);

var isDrawing = false;
var prevX = 0;
var prevY = 0;
var currX = 0;
var currY = 0;

function buttonClick() {
  console.log('Clicked!');
  var height = video.videoHeight;
  var width = video.videoWidth;
  canvas.width = width;
  canvas.height = height;
  ctx.fillRect(0, 0, width, height);
  ctx.drawImage(video, 0, 0, width, height);
}

function setCoordinates(e) {
  prevX = currX;
  prevY = currY;

  var boundingClientRect = e.target.getBoundingClientRect();
  var left = boundingClientRect.left;
  var top = boundingClientRect.top;

  currX = e.clientX - left;
  currY = e.clientY - top;
}

function mouseDown(e) {
  setCoordinates(e);
  isDrawing = true;
}

function mouseUp(e) {
  isDrawing = false;
}

function mouseMove(e) {
  if (!isDrawing) {
    return;
  }

  setCoordinates(e);
  draw();
}

function draw() {
    ctx.beginPath();
    ctx.moveTo(prevX, prevY);
    ctx.lineTo(currX, currY);
    ctx.strokeStyle = "red";
    ctx.lineWidth = 2;
    ctx.stroke();
    ctx.closePath();
}
javascript html5 html5-canvas html5-video drawing
1个回答
0
投票

从画布中删除CSS样式将解决问题。如果你需要更大的画布,请使用canvas.width和canvas.height属性。使用css控制画布大小只会增加html元素大小,但不会增加绘图表面(像素)。

要删除的CSS:

 flex: 1;
 width: 100%;
© www.soinside.com 2019 - 2024. All rights reserved.