【问题标题】:HTML Canvas, How do you create a circle at the position of the mouse when clicked and then for the circle to increase in radius?HTML Canvas,如何在单击鼠标时在鼠标位置创建一个圆圈,然后使圆圈的半径增加?
【发布时间】:2017-10-06 20:19:45
【问题描述】:

所以,我自己尝试过,并在网上大量搜索,但我似乎无法解决这个特定问题。我正在尝试制作一个非常简单的效果,看起来像一个非常基本的水波纹。我打算让用户能够单击画布上的某处,并在鼠标单击的位置(从零半径开始)出现一个空圆圈(带有黑色笔划),并作为动画不断扩大半径.

我目前有这个代码:

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

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

			radius++;

			requestAnimationFrame(ripple);
		}

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

这是它目前所做的: Screenshot

非常感谢任何帮助!

【问题讨论】:

    标签: html animation canvas geometry


    【解决方案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}
    &lt;canvas id="canvas" width="635" height="208"&gt;&lt;/canvas&gt;

    注意:使用e.offsetXe.offsetY 获得相对于画布的正确鼠标坐标。

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 2015-09-12
      相关资源
      最近更新 更多