2016-12-13 59 views
0

我有一個尺寸爲300x300的固定HTML5畫布。我正在調整頁面上的其他圖像,以通過Javascript獲得300px的最大寬度/高度(取決於哪個維度更大)。Javascript:可變大小的圖像在固定尺寸的畫布上

雖然這並不實際調整源圖像的大小,但是當我在畫布上繪製它們時,會使用原始大小。

有沒有一種辦法:

  1. 使用JavaScript調整這些圖像,使他們繪製在畫布上用300像素,最大高度或寬度。

AND

  • 具有畫布保持其300x300的尺寸與它裏面的尺寸調整的圖像,從而可將具有可變大小的圖像的300×300正方形完全包含的內部它被創建?
  • (想想製作300x300的Photoshop文件,你的各種圖像下降,他們調整大小以適應)

    這甚至可能使用Javascript /月?

    編輯

    這裏是我結束了使用基於公認的答案代碼:我已經創建了一個嘗試匹配上述情形說明了小提琴

    var ssItems = [exampleUrls], //array of image paths 
    imgHolder = document.getElementById("img-holder"); 
    
    for (var i = 0; i < ssItems.length; i++) { 
          var img = new Image(), 
          imgSrc = "/ItemImages/Large/" + ssItems[i] + ".jpg", 
          imgW, 
          imgH; 
          img.src = imgSrc; 
          img.onload = function() { 
           var canvas = document.createElement("canvas"), 
           ctx = canvas.getContext("2d"); 
           canvas.setAttribute("class", "img-canvas"); 
           canvas.setAttribute("width", "300"); 
           canvas.setAttribute("height", "300"); 
           imgHolder.appendChild(canvas); 
           imgW = (canvas.height * this.width)/this.height; 
           imgH = (canvas.width * this.height)/this.width; 
           if (this.height > this.width) { 
           ctx.drawImage(this, canvas.width/2 - imgW/2, 0, imgW, canvas.height); 
           } else { 
           ctx.drawImage(this, 0, canvas.height/2 - imgH/2, canvas.width, imgH); 
           } 
          } 
    
    +0

    你的意思是像[這裏](https://stackoverflow.com/questions/21961839/simulation-background-size-cover-in-canvas/21961894#21961894)或類似[this](https://stackoverflow.com/questions/14087483/how-to-proportionally-resize-an-image-in-canvas/14087607#14087607)? – K3N

    +0

    甚至[SVG風格](http://stackoverflow.com/questions/34428723/how-to-implement-svgs-preserveaspectratio-xminymin-slice-for-canvas-drawimage/34429774#34429774)? – Kaiido

    +0

    @ K3N類似,是的,儘管它看起來像這個例子模仿'background-size:cover'或者一個「縮放」效果。不過,這篇博文很有幫助。 – Tier

    回答

    2

    var canvas = document.getElementById('myCanvas'); 
    var ctx = canvas.getContext("2d"); 
    
    var image = new Image(); 
    image.src = 'http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg'; 
    
    // calculates width and height with respect to canvas 
    var width = (canvas.height * image.width)/image.height; 
    var height = (canvas.width * image.height)/image.width; 
    
    // takes width or height full choosing the larger value and centers the image 
    if(image.height > image.width){ 
        ctx.drawImage(image, canvas.width/2 - width/2, 0, width, canvas.height); 
    }else{ 
        ctx.drawImage(image, 0, canvas.height/2 - height/2, canvas.width, height); 
    } 
    

    你可以看看到它:https://jsfiddle.net/q8qodgmn/1/

    +0

    不得不稍微修改代碼以適合我的特定項目(將width/height聲明和if/else語句移動到'image.onload'中),但它按預期工作,謝謝! – Tier