将图像放在画布JS上

时间:2017-03-29 14:31:15

标签: javascript html css html5-canvas drawimage

我在html中有以下内容:

<img id="MarkingImage"></img>                
<canvas id="MarkingCanvas"></canvas>

css

#MarkingCanvas { width: 100%; background-color: #7986CB; height: 96%; }
#MarkingImage { position: absolute; }

js

function LoadImage()
{
   var markingImage = new Image();

   markingImage.addEventListener('load', function() 
   {
       m_imageWidth = this.naturalWidth;
       m_imageHeight = this.naturalHeight;

       m_markingCanvasContext.drawImage(markingImage, 0, 0, m_imageWidth,  m_imageHeight);
   });
   markingImage.src = 'PICT0001.JPG';
}

问题是这个输出会拉伸图像并且它的质量变得非常差(参见附件“原始”和“结果”)。 Original Image

Result Image

当我调试时,我可以看到尺寸如果我的画布是:

width - 1410 height - 775

我的图片尺寸为:

width - 551 height - 335

所以我的问题是:为什么图像不是原始大小?我的意思是,画布上有足够的空间。此外,为什么图像会被拉伸,结果导致图像质量很差。看起来像是超出了画布的大小。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

您需要根据浏览器窗口的宽度和高度动态设置画布宽度和高度。此外,无需使用图像naturalWidth / naturalHeight

&#13;
&#13;
var m_markingCanvas = document.getElementById('MarkingCanvas');
var m_markingCanvasContext = m_markingCanvas.getContext('2d');

// setting canvas width and height dynamically
m_markingCanvas.width = window.innerWidth;
m_markingCanvas.height = window.innerHeight;

function LoadImage() {
    var markingImage = new Image();
    markingImage.addEventListener('load', function() {
        m_markingCanvasContext.drawImage(this, 0, 0);
    });
    markingImage.src = 'https://i.stack.imgur.com/a3Wpy.jpg';
}
LoadImage();
&#13;
<canvas id="MarkingCanvas"></canvas>
&#13;
&#13;
&#13;