2012-08-17 131 views
1

我目前正在研究涉及畫布元素的項目,並在調整畫布大小時遇到​​問題。我試圖通過將寬度和高度除以2來在畫布中心繪製圖像,但是每當我調整畫布大小時,它只會更改HTML,因此當我重新繪製圖像時,仍然會畫一半舊畫布的寬度和高度。我不確定這是否是一個DOM問題或什麼,但將不勝感激任何幫助。代碼HTML5畫布僅調整大小html

<body> 
<div id="holder"> 
<div id="dropdown"> 
    <div id="ddcontents" style="display: none;"> 
    <button onclick="fade()">Options</button> 
    <button onclick="getSize()">Canvas Size</button> 
    <button onclick="redraw()" disabled="true">Redraw</button> 
    </div> 
</div> 
<canvas id="c" height="480" width="640">Your browser does not support HTML5.</canvas> 
<div id="options" style="display: none"> 
<div id="optcontent" style="display: none"> 
    <center><h1>Options</h1></center>  
    <div id="sound"> 
     <div>Volume: 
      <form oninput="volumenumber.value = parseInt(volume.value)"> 
       <input type="range" name="volume" min="0" max="100" value="80" disabled="true"> 
       <input type="hidden" name="hello" value="%"> 
       <output name="volumenumber" for="volume">80</output> 
      </form> 
      Resolution: 
      <select id="resolution"> 
       <option value="480p">480x640</option> 
       <option value="720p">720x1280</option> 
      </select> 
     </div> 
    </div> 
    <div id="closeoptions"> 
     <button onclick="apply()">Apply</button> 
     </div> 
    </div> 
</div> 

</div> 


<script src="options.js"></script> 
</body> 
</html> 

而對於JS:我在Safari瀏覽器,FF和Chrome

編輯測試

var c = document.getElementById('c'); 
var ctx=c.getContext("2d"); 
var img=new Image(); 
var w = this.c.clientWidth; // stores the width for later use 
var h = this.c.clientHeight; 
this.c.width = w; 
this.c.height = h; 
var cwidth = c.width; 
var cheight = c.height; 

img.onload = function(){ 
ctx.drawImage(img,w/2 - 14,h/2 - 19); 
}; 
img.src="image_preview.png"; 


function apply() 
{ 
var reso = document.getElementById("resolution"); 
var resol = reso.options[reso.selectedIndex].value; 
//alert(resol) 
if (resol == "720p") 
{ 
    //alert("You changed to 720p"); 
    h = 720; 
    w = 1280; 
    cheight = 720; 
    cwidth = 1280; 
} 
else if (resol == "480p") 
{ 
    //alert("You changed to 480p"); 
    h = 480; 
    w = 640; 
    cheight = 480; 
    cheight = 640; 
} 
getSize(); 
redraw(); 
} 

function redraw() 
{ 
ctx.drawImage(img,w/2 - 14,h/2 - 19); 
img.src="image_preview.png"; 
} 

function getSize() 
{ 
alert(h + "x" + w); 
} 
+1

如果你可以在jsfiddle.net或jsbin.com上發佈你的代碼來展示問題,它會讓某人更容易確定什麼是錯誤的。 – 2012-08-17 18:05:48

+0

發表,與dystroy的編輯。 – 2012-08-17 18:37:18

回答

0

使用你有帆布,確保它的內部結構具有相同呈現html區域的大小。

你可以這樣做:

this.canvas.width = this.canvas.clientWidth; 
this.canvas.height = this.canvas.clientHeight; 

平時我還保存這些方面對我的渲染計算:

var w = this.canvas.clientWidth; // stores the width for later use 
var h = this.canvas.clientHeight; 
this.canvas.width = w; 
this.canvas.height = h; 

編輯:改變元件尺寸,先例之前做這樣的事情代碼:

$('#mycanvas').width(newWidthInPx); 
+0

好吧,這似乎解決了一半的問題,我使用的警報的確確實驗了畫布大小的改變,但畫布本身的大小並沒有改變。 – 2012-08-17 18:27:05