2014-10-20 72 views
0

我正在繪製一個大型的畫布圖像作爲背景,圖像大於窗口大小。我想知道是否有一種方法可以讓我將圖像集中在全屏幕上。如果是這樣,怎麼樣?這是我在做什麼:我可以居中畫布圖像

 var canvas = document.getElementById('canvas'), 
      context = canvas.getContext('2d'); 

     window.addEventListener('resize', resizeCanvas, false); 

     function resizeCanvas() { 
      canvas.width = window.innerWidth; 
      canvas.height = window.innerHeight; 

      drawStuff(); 
     } 

     resizeCanvas(); 

     function drawStuff() { 
      var imageObj = new Image(); 

      imageObj.onload = function() { 
       context.drawImage(imageObj, 69, 50); 
      }; 

      imageObj.src = '/resources/img/bg.png'; 
     }   

回答

3

這裏是定心的圖像不使用變換以帆布的可選方式(也參見下面的註釋):

imageObj.onload = function() { 

    var x = (canvas.width - this.width) * 0.5, // this = image loaded 
     y = (canvas.height - this.height) * 0.5; 

    ctx.drawImage(this, x, y); 
}; 

由於圖像比畫布x和y較大將是負的在這種情況下,這非常好。如果圖像較小,它也可以工作。如果您在負載處理程序外執行繪圖,則當然需要使用imageObj而不是this

注意:您設置resize處理程序的方式不是處理圖像重新定位的最佳方式 - 您應該只加載一次圖像,然後重新使用該對象。由於調整大小通常會創建大量事件,因此會觸發相同數量的圖像重新加載。

爲此才能正常工作,你可以做這樣的事情,而不是:

var canvas = document.getElementById('canvas'), 
    context = canvas.getContext('2d'), 

    imageObj = new Image(); // declare globally 

imageObj.onload = function() { 

    // now set up handler when image is actually loaded 
    // - else drawImage will fail (width, height is not available and no data) 
    window.addEventListener('resize', resizeCanvas, false); 

    // initial call to draw image first time 
    resizeCanvas(); 
}; 

imageObj.src = '/resources/img/bg.png'; 

function resizeCanvas() { 
    canvas.width = window.innerWidth; 
    canvas.height = window.innerHeight; 

    drawStuff(); 
} 

function drawStuff() { 
    var x = (canvas.width - imageObj.width) * 0.5, 
     y = (canvas.height - imageObj.height) * 0.5; 

    ctx.drawImage(imageObj, x, y); 
}   

它不是完美的,因爲resize事件隊列仍然會很大,可能會滯後 - 這是你的解決方案也是如此,例如this one (稍作修改)。

+1

thx! - 這有助於很多* – Louis 2014-10-20 19:32:27

1

以下是如何將圖像居中在畫布上。任何垂直或水平溢出將是非畫布的:

imageObj.onload = function() { 
    ctx.translate(canvas.width/2,canvas.height/2); 
    ctx.drawImage(imageObj,-imageObj.width/2,-imageObj.height/2); 
    ctx.translate(-canvas.width/2,-canvas.height/2); 
}; 

祝您的項目順利!