2013-06-11 35 views
0

我有一條簡單的直線,由貝塞爾曲線繪製。挑戰在於改變它轉換的位置,即如果曲線的高度增加或減少,它應該發生在轉換中,而不是突然發生。所以我的問題是提供畫布上鼠標懸停的過渡?如何提供過渡到曲線?過渡到畫布中繪製的曲線?

canvas = document.getElementById("canvas"); 
ctx = canvas.getContext("2d") 
ctx.lineWidth = 6; 
ctx.strokeStyle = "#333"; 
ctx.beginPath(); 
ctx.moveTo(328, 347); 
ctx.bezierCurveTo(326, 387, 326, 386, 326, 420); 
ctx.stroke(); 

回答

3

您可以使用requestAnimationFrame在mouseenter上爲曲線設置動畫。

這是做動畫的功能:

最佳實踐正在轉向使用requestAnimationFrame代替的setInterval。此代碼將RAF封裝在超時內以控制幀速率。

function draw() { 
    setTimeout(function() { 

     // request another loop 
     requestAnimationFrame(draw); 

     // animate the control point 
     cpY+=movement; 
     if (cpY<50 || cpY>250){movement= -movement;}   

     // draw the new bezier 
     ctx.clearRect(0,0,canvas.width,canvas.height); 
     ctx.beginPath(); 
     ctx.moveTo(100,150); 
     ctx.quadraticCurveTo(150,cpY,200,150); 
     ctx.lineWidth=10; 
     ctx.stroke(); 

    }, 1000/fps); 
} 

這裏是代碼和一個小提琴:http://jsfiddle.net/m1erickson/p5snk/

<!doctype html> 
<html> 
<head> 
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> 
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 

<style> 
    body{ background-color: ivory; } 
    canvas{border:1px solid red;} 
</style> 

<script> 
$(function(){ 

    var canvas = document.getElementById("canvas"); 
    var ctx = canvas.getContext("2d"); 

    var cpY = 150; 
    var movement = -8; 
    var fps = 60; 

    $("#canvas").mouseenter(function() { 
     cpY = 150; 
     movement = -10; 
     draw(); 
    }); 
    $("#canvas").mouseleave(function() { 
     cpY = 50; 
     movement = 15; 
     draw(); 
    }); 

    drawLine(); 

    function drawLine() { 
     ctx.clearRect(0, 0, canvas.width, canvas.height); 
     ctx.beginPath(); 
     ctx.moveTo(100, 150); 
     ctx.lineTo(200, 150); 
     ctx.lineWidth = 10; 
     ctx.stroke(); 
    } 

    function draw() { 
     setTimeout(function() { 

      if (cpY < 50) { 
       return; 
      } 
      if (cpY > 150) { 
       drawLine(); 
       return; 
      } 

      // request another loop 
      requestAnimationFrame(draw); 

      // animate the control point 
      cpY += movement; 

      // draw the new bezier 
      ctx.clearRect(0, 0, canvas.width, canvas.height); 
      ctx.beginPath(); 
      ctx.moveTo(100, 150); 
      ctx.quadraticCurveTo(150, cpY, 200, 150); 
      ctx.lineWidth = 10; 
      ctx.stroke(); 

     }, 1000/fps); 
    } 

}); // end $(function(){}); 
</script> 

</head> 

<body> 
    <canvas id="canvas" width=300 height=300></canvas> 
</body> 
</html> 
+0

:我很欣賞你的努力,完全瞭解如何操作控制點,但關於過渡效果什麼的javascript怎麼給過渡曲線?在畫布中 –

+1

仍然不確定我明白...當鼠標進入畫布時,您是否想要將曲線變成曲線?如果是這樣,我編輯了我的答案來做到這一點。 – markE

+1

+1尼斯小提琴! – Jarrod