2017-05-08 33 views
0

所以,我試圖嘗試這一點,並在網上搜索了很多,我似乎無法解決這個問題。我試圖做出一個非常簡單的效果,看起來像一個非常基本的水波紋。我打算讓用戶能夠點擊畫布上的某個位置,並在鼠標點擊的地方出現一個空圓圈(黑色筆畫),並以半徑爲零的方式連續展開半徑。HTML畫布,如何在點擊鼠標的位置時創建一個圓,然後在圓上增加半徑?

我現在有這樣的代碼:

<!DOCTYPE html> 
 
<html> 
 
\t <head> 
 
    \t \t <!-- Search Engine Optimisation (SEO) --> 
 
    \t \t <title> Ripple </title> 
 
    \t \t <meta description="Codelab assignment 3"> 
 
    \t \t <meta keywords="Uni, assignment, ripple, interactive, discovery"> 
 
    \t \t <!-- End of Metadata --> 
 
    \t \t <!-- Links --> 
 
    \t \t <link rel="stylesheet" type="text/css" href="style.css"> 
 
    \t </head> 
 
    \t <body> 
 
    \t \t <canvas id="myCanvas" width="1024" height="768" style="border: 1px solid"></canvas> 
 
\t </body> 
 
\t <script type="text/javascript"> 
 
\t \t var canvas = document.getElementById("myCanvas"); 
 
\t \t var ctx = canvas.getContext("2d"); 
 
\t \t var canvasWidth = canvas.width; 
 
\t \t var canvasHeight = canvas.height; 
 
\t \t var radius = 0; 
 
\t \t 
 
\t \t //Have a rectangle fill the canvas and add a hit region 
 
\t \t //Call the ripple function from the rectangle function 
 
\t \t //Track mouse position in rectangle 
 

 
\t \t function ripple(e) { 
 
\t \t \t // ctx.clearRect(0, 0, canvasWidth, canvasHeight); 
 
\t \t \t ctx.beginPath(); 
 
\t \t \t ctx.arc(e.clientX,e.clientY,radius,0,2*Math.PI); 
 
\t \t \t //ctx.closePath(); 
 
\t \t \t ctx.stokeStyle = "black"; 
 
\t \t \t ctx.stroke(); 
 

 
\t \t \t radius++; 
 

 
\t \t \t requestAnimationFrame(ripple); 
 
\t \t } 
 

 
\t \t canvas.addEventListener('mousedown', ripple); 
 
\t </script> 
 
</html>

這是它目前的作用: Screenshot

我真的很感激任何幫助!

回答

1

你必須通過requestAnimationFrame調用ripple功能時,通過鼠標事件

也,你需要設置的半徑來0和明確的運行動畫幀(如果有的話)上點擊鼠標

var canvas = document.getElementById("canvas"); 
 
var ctx = canvas.getContext("2d"); 
 
var canvasWidth = canvas.width; 
 
var canvasHeight = canvas.height; 
 
var radius = 0; 
 
var rAF; 
 

 
function ripple(e) { 
 
    ctx.clearRect(0, 0, canvasWidth, canvasHeight); 
 
    ctx.beginPath(); 
 
    ctx.arc(e.offsetX, e.offsetY, radius, 0, 2 * Math.PI); 
 
    ctx.stokeStyle = "black"; 
 
    ctx.stroke(); 
 
    radius++; 
 
    rAF = requestAnimationFrame(function() { 
 
     ripple(e); 
 
    }); 
 
} 
 
canvas.addEventListener('mousedown', function(e) { 
 
    if (rAF) cancelAnimationFrame(rAF); 
 
    radius = 0; 
 
    ripple(e); 
 
});
body{margin:10px 0 0 0;overflow:hidden}canvas{border:1px solid #ccc}
<canvas id="canvas" width="635" height="208"></canvas>

注:使用e.offsetXe.offsetY以獲得相對於畫布的正確鼠標座標。

相關問題