在画布上绘制图像

时间:2019-03-19 08:55:30

标签: javascript html5 html5-canvas html5-video drawing

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

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

最小再现: 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();
}

1 个答案:

答案 0 :(得分:0)

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

要删除的CSS:

 flex: 1;
 width: 100%;