我是画布的新手,我正在玩它。
我想在鼠标点击上绘制一个圆圈,并且应该通过鼠标拖动来确定圆的半径(类似于在窗口中绘制的绘图圆)
我试过创建一个圆圈,但是这样做了 我的代码
<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>
我在plunker中的代码 http://plnkr.co/edit/DPa9km1hHAAsCBCbnGvB?p=preview
如果有人帮助我,我会很高兴
提前致谢
答案 0 :(得分:-2)
一般的意思是你必须得2分,圆圈中心的那个(这是用户按下鼠标的地方),以及鼠标移动的当前点
两点之间的距离将是半径,由毕达哥拉斯定理h^2 = c^2 + c^2
给出:
这里有一些示例代码,根据您的需要进行修改
<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>