2015-11-04 43 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