画布使用drawImage进行拉伸 [英] Canvas is stretching using drawImage

查看:919
本文介绍了画布使用drawImage进行拉伸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道必须使用 width 来设置< canvas> code> height 属性以避免伸展。

I am aware of having to set the size of a <canvas> element using the width and height attribute to avoid stretching. I have no CSS applied to it other than background-color.

我使用 ctx.drawImage()显示视频。 奇怪的是,我的 640x480 视频播放正常,没有伸展。

I am using ctx.drawImage() to show a video. The weird thing is, my 640x480 video plays fine and is not stretched. It is only happening on my 640x360 videos for now.

我已经创建了一个angular命令将视频绘制到画布元素上,除了拉伸之外,它都可以工作。这是我的代码,将视频元素绘制到画布上:

I have created an angular directive that draws video onto a canvas element and it all works except for the stretching. Here is my code that draws the video element onto the canvas:

scope.renderPlayer = function()
{
  var $this = this;
  attributes.width = player.videoWidth;
  attributes.height = player.videoHeight;
  canvas.setAttribute('width', attributes.width);
  canvas.setAttribute('height', attributes.height);

  (function loop()
  {
    if (!$this.paused && !$this.ended)
    {
      ctx.drawImage($this, 0,0, attributes.width, attributes.height);
      setTimeout(loop, 1000/30);
    }
  })();
};
player.addEventListener('play', scope.renderPlayer);

我向你保证,视频的源没有底部的拉伸假象,下面的图像(你可以真正看到像素拉伸在右下角)。我的canvas元素的初始宽度和高度为640x480,它将根据加载的视频的大小而改变。

I assure you the source of the videos don't have that stretching artifacting on the bottom as shown in the image below (You can really see the pixels stretched on the bottom right). My initial width and height of the canvas element is 640x480 and it will change depending on the size of the loaded video.

推荐答案

让我知道,如果这个CSS修复它,我需要它每当我使用canvas:

Let me know if this CSS fixes it for you, I need it whenever I use canvas:

canvas {
    display: block;
}

canvas 容易受到与 img 标记相同的缺陷,因为它在它下面产生额外的空间。你是正确的设置维度作为HTML属性虽然,多么痛苦。

the canvas tag is susceptible to the same pitfalls as the img tag in that it renders extra space below it. You are correct to set the dimensions as HTML attributes though, what a pain.

这篇关于画布使用drawImage进行拉伸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆