2017-05-08 158 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以获得相对于画布的正确鼠标坐标。