簡體   English   中英

畫布使用drawImage拉伸

[英]Canvas is stretching using drawImage

我知道必須使用widthheight屬性設置<canvas>元素的大小,以避免拉伸。 除了background-color外,我沒有將CSS應用於它。

我正在使用ctx.drawImage()來顯示視頻。 奇怪的是,我的640x480視頻可以正常播放並且沒有拉伸。 目前,這僅在我的640x360視頻中發生。

我創建了一個角度指令,該指令將視頻繪制到畫布元素上,除了拉伸之外,所有其他指令均有效。 這是將視頻元素繪制到畫布上的代碼:

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,它會根據加載的視頻的大小而變化。

在底部伸展

讓我知道此CSS是否為您修復了它,每當我使用canvas時都需要它:

canvas {
    display: block;
}

canvas標簽易受與img標簽相同的陷阱的img ,因為它在其下方提供了額外的空間。 您將尺寸設置為HTML屬性是正確的,這很麻煩。

我已經有一段時間沒有使用canvas了,但是您可以嘗試ctx.drawImage($this) ,也可以requestAnimationFrame並使用它代替setTimeout

scope.renderPlayer = function()
{
  var $this = this;
  canvas.width = player.width;    // if canvas is a Jquery Object, try canvas[0].width
  canvas.height = player.height;    // if canvas is a Jquery Object, try canvas[0].height

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM