2017-05-07 172 views
1

使用drawImage「調整」圖像的大小;drawImage將所有圖片的大小調整爲相同的寬度

img.onload = function(){ 
      var width = img.width * 0.16, 
       height = img.height * 0.16; 

      canvas.width = width, 
      canvas.height = height; 


      ctx.imageSmoothingEnabled = false; 

      ctx.drawImage(img, 0, 0, width, height); 
     } 

每當使用它像這樣,它示出了圖像很好地

但每當我不固定的寬度和高度它顯示了初始化有點模糊 img.onload =函數(){

  ctx.imageSmoothingEnabled = false; 

      ctx.drawImage(img, 0, 0, 56, 56); 
     } 

所以我想固定的高度和寬度,但必須顯示不模糊

回答

0

您的第一個版本設置畫布的寬度和高度是相同的尺寸a那麼當您繪製圖像時,不會執行縮放(實際上,您的img的寬度和高度會縮小16%或0.16,以匹配您指定的值,但它不會縮放圖像因爲drawImage()的最後2個參數與畫布的尺寸相匹配時,繪製到畫布中)。

img.onload = function(){ 
      var width = img.width * 0.16, 
       height = img.height * 0.16; 

      canvas.width = width, // canvas's width === img's width 
      canvas.height = height; // canvas's heeight === img's height 


      ctx.imageSmoothingEnabled = false; 

      ctx.drawImage(img, 0, 0, width, height); // draw img at the same dimensions as those of the canvas => no scaling => no blur 
     } 

然而,你的第二個版本的56x56大小繪製圖像,這不符合畫布的尺寸,因此圖像按比例縮小,所以它看起來有點模糊。

img.onload = function(){ 

     ctx.imageSmoothingEnabled = false; 

     ctx.drawImage(img, 0, 0, 56, 56); // last 2 arguments tell the browser to draw the image at 56x56 px dimensions 
    } 
+0

謝謝,但我注意到,問題是如何做到這一點工作呢? –

+0

@JohnSmiths不會過多地縮放它 – Dummy

相關問題