2012-05-25 202 views
8

我有一個尺寸爲979X482px的畫布元素,我想將它拉伸以適應任何給定瀏覽器窗口的寬度,保持寬高比爲1到1,我希望高度相對於畫布的寬度縮放。任何建議如何去做這個與JavaScript/jQuery?縮放保留寬高比的HTML5畫布寬度

+1

計算新的寬度和高度,並通過jquery/javascript應用它們。關於如何計算維度的比例,有大量的信息。你有沒有嘗試過自己?有些代碼可能會遇到問題? – Yoshi

回答

5

首先你畫布的寬度設置爲100%

$('#canvas').css('width', '100%'); 

然後在其寬度

$(window).resize(function(){ 
    $('#canvas').height($('#canvas').width()/2.031); 
}); 

2.031 =482分之979

更新其高度的底座但你不應該附加to $(window).resize like me ...這是一個不好的行爲

+0

謝謝你,但我似乎無法得到它的工作。 ($''canvas')。height($('#canvas')。width()應該是$('#canvas')。height($('canvas')。width()/ 2.031)/2.031);',注意到ID? – dcd0181

+0

是的,我忘了把#canvas –

+0

這會導致內容模糊。作爲其他答案狀態,您需要操作畫布上下文。 – cyberwombat

-2

試試這個

$('#canvas').css('width', $(window).width()); 
$('#canvas').css('height', $(window).height()); 
+1

這不是保持比例 –

+1

這不設定比例,它只是將畫布尺寸設置爲窗口寬度和窗口高度。 – shadryck

9
ctx.canvas.width = window.innerWidth; 

ctx.canvas.height = 3*window.innerWidth/4; 

或一些變化。 ctx是上下文。對於邊緣案例的if語句可能是必要的!

0

我一直在玩這個一段時間我自己。這個概念圍繞着瞭解畫布的寬度展開。您還需要確保您的所有canvas資源也使用計算來依靠瀏覽器進行發佈。我記錄了我的代碼,我希望它有幫助,

<body> 

    // in style make your canvas 100% width and hight, this will not flex for all browsers sizes. 

<style> 

canvas{ 
    width: 100%; 
    height:100%; 
    position: relative; 
} 

</style> 

<canvas id="myCanvas"></canvas> 

<script> 

// here we are just getting the canvas and asigning it the to the vairable context 

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

// no we get with of content and asign the same hight as the with. this gives up aspect ration 1:1. 

    context.canvas.width = window.innerWidth; 
    context.canvas.height = window.innerWidth; 

// If you want aspect ration 4:3 uncomment the line below. 
//context.canvas.height = window.innerWidth; 

</script> 

</body> 
相關問題