2015-11-04 48 views
0

我試圖順利調整html5 canvas元素的大小。我已經拼湊了一些代碼,我認爲以下應該可以工作:使用javascript調整html canvas的大小

<body> 
    <header id='myheader' height='200'> 
     <canvas id='mycanvas' width='200' height='200'></canvas> 

     <script> 

     var mycanvas = document.getElementById('mycanvas'); 
     var context = mycanvas.getContext('2d'); 
     var centerX = mycanvas.width/2; 
     var centerY = mycanvas.height/2; 
     var radius = 70; 

     context.beginPath(); 
     context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); 
     context.fillStyle = 'blue'; 
     context.fill(); 
     context.lineWidth = 5; 
     context.strokeStyle = '#003300'; 
     context.stroke(); 

     var animate = function(prop, val, duration) { 
      var start = new Date().getTime(); 
      var end = start + duration; 
      var current = mycanvas[prop]; 
      var distance = val - current; 
      var step = function() { 
       var timestamp = new Date().getTime(); 
       var progress = Math.min((duration - (end - timestamp))/duration, 1); 
       mycanvas[prop] = current + (distance * progress); 
       if (progress < 1) requestAnimationFrame(step); 
      }; 
      return step(); 
     }; 

     animate('mycanvas.height', 10, 1000); 

     </script> 
    </header>  
</body> 

......但顯然它不!我正在尋找的結果是一個縮小的畫布,以顯示圓圈的中間部分(比稍後會添加一個圓圈更有趣)。有什麼顯而易見的,我錯過了,或者我只是做錯了這種方式?最終我想同時調整畫布和標題的大小,所以讓畫布大小調整到第1階段。任何幫助讚賞...

(編輯:其實,我最終希望調整畫布和標題響應滾動事件 - 我認爲這意味着避免一個CSS的解決方案 - 但我想獲得該位第一個工作日)

回答

1

這裏有你的腳本的幾個變化,我相信你想要做什麼:

var mycanvas = document.getElementById('mycanvas'); 
    var context = mycanvas.getContext('2d'); 
    var radius = 70; 

    function draw() { 
     var centerX = mycanvas.width/2; 
     var centerY = mycanvas.height/2; 

     context.beginPath(); 
     context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); 
     context.fillStyle = 'blue'; 
     context.fill(); 
     context.lineWidth = 5; 
     context.strokeStyle = '#003300'; 
     context.stroke(); 
    } 

    var animate = function(target, prop, val, duration, action) { 
     var start = new Date().getTime(); 
     var end = start + duration; 
     var current = target[prop]; 
     var distance = val - current; 
     var step = function() { 
      var timestamp = new Date().getTime(); 
      var progress = Math.min((duration - (end - timestamp))/duration, 1); 
      target[prop] = current + (distance * progress); 
      action(); 
      if (progress < 1) requestAnimationFrame(step); 
     }; 
     return step(); 
    }; 

    animate(mycanvas, 'height', 10, 1000, draw); 
+0

謝謝!這正是我想要它做的 - 極大的幫助。 – user219142