问题描述
我是画布的新手,我正在玩它。
Im new to canvas and i was playing around with it.
我想在鼠标单击上绘制一个圆,并且圆的半径应由鼠标拖动来决定(类似于在Windows的绘制中绘制圆 )
I wanted to draw a circle on mouse click and radius of circle should be decided by mouse drag (similar to drawing circle in Paint in windows )
我尝试创建一个圆,但在我的代码中完成了
的尝试
i have tried creating a circle but struck doing thismy code
<html>
<head>
</head>
<body style="margin:0">
<canvas id="canvas" width="500" height="500" style="border:1px solid"></canvas>
<script>
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
var radius=50;
var putPoint = function(e){
context.beginPath();
context.arc(e.clientX, e.clientY, radius, 0, Math.PI*2);
context.fill();
}
canvas.addEventListener('mousedown',putPoint);
</script>
</body>
</html>
我在插件中的代码
如果有人帮助我
提前感谢
推荐答案
通常的想法是必须获得2个点,其中一个点将位于圆心(这是用户按下鼠标的位置),而当前点位于此处鼠标移动
the general ideia is that you have to take 2 points, the one there circle center will be (this is where the user presses the mouse), and the current point, where the mouse is moving
两个点之间的距离将是半径,并由勾股定理给出 h ^ 2 = c ^ 2 + c ^ 2
这样:
the distance between the 2 points will be the radius, and is given by the Pythagorean theorem h^2 = c^2 + c^2
so:
- onmousedown将该点保存为中心
- omousemove计算到中心的距离并用作半径
- omouseup停止操作/动画
这是一些示例代码,根据您的需要进行修改
here is some sample code, modify to your needs
<html>
<head>
</head>
<body style="margin:0">
<canvas id="canvas" width="500" height="500" style="border:1px solid"></canvas>
<script>
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
var radius=50;
var nStartX = 0;
var nStartY = 0;
var bIsDrawing = false;
var putPoint = function(e){
nStartX = e.clientX;nStartY = e.clientY;
bIsDrawing = true;
radius = 0;
}
var drawPoint = function(e){
if(!bIsDrawing)
return;
var nDeltaX = nStartX - e.clientX;
var nDeltaY = nStartY - e.clientY;
radius = Math.sqrt(nDeltaX * nDeltaX + nDeltaY * nDeltaY)
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.arc(nStartX, nStartY, radius, 0, Math.PI*2);
context.fill();
}
var stopPoint = function(e){
bIsDrawing = false;
}
canvas.addEventListener('mousedown',putPoint);
canvas.addEventListener('mousemove',drawPoint);
canvas.addEventListener('mouseup',stopPoint);
</script>
</body>
</html>
这篇关于HTML Canvas单击鼠标并画一个圆并将其拖动,直到获得所需的半径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!