Javascript元素中出现奇怪的工件



我有两个按钮在一个html页面移动一行围绕一个圆圈,我希望总是只有一行,但当按钮按下足够的行是在圆的下半部分顺时针移动额外的线出现实际的文字是按钮,因为我在实际页面上使用图标作为按钮,将其设置为用于更多编辑的按钮。

因为我被告知我有太多的代码,我删除了3行css,所以即使文字不改变颜色或页面上的任何东西,他们仍然可以点击来移动手臂

var pos = 0; //global variable
var inc = 0.1;
function clockwise() {
pos -= inc;
drawCircle();
}
function counter() {
pos += inc;
drawCircle();
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.9;
setInterval(drawCircle, 0);
function drawCircle() {
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fillStyle = "white";
ctx.fill();
drawHand(ctx, pos, radius * 0.9, radius * 0.02);
}
function drawHand(ctx, pos, length, width) {
ctx.beginPath();
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.moveTo(0, 0);
ctx.rotate(pos);
ctx.lineTo(0, -length);
ctx.stroke();
ctx.rotate(-pos);
}
<p><b1 id="left" onclick="clockwise()">counter-clockwise</b1></p>                 
<p><b3 id="right" onclick="counter()">clockwise</b3></p>
<canvas id="canvas" width="240" height="240" style="background-color:transparent"></canvas>

圆弧图也是路径

改变:

function drawCircle() {
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fillStyle = "white";
ctx.fill();
drawHand(ctx, pos, radius * 0.9, radius * 0.02);
}

:

function drawCircle() {
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fillStyle = "white";
ctx.fill();
drawHand(ctx, pos, radius * 0.9, radius * 0.02);
}

正如@Mike'Pomax'Kamermans所说,你也应该在每次开始绘制新框架之前清除绘图区域。您还可以在旋转之前保存上下文状态,并在执行所需操作之后恢复之前的状态。这样做,您将不需要旋转回等量的弧度。我也把增量改为度数。我重写了你的代码,看看:

var pos = 0;
var inc = 30;
function clockwise() {
pos -= inc * Math.PI / 180.0;
}
function counter() {
pos += inc * Math.PI / 180.0;
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.9;
setInterval(drawCircle, 0);
function drawCircle() {
ctx.clearRect( -radius-10, -radius-10, radius*2+10, radius*2+10 );
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fillStyle = "white";
ctx.fill();
drawHand(pos, radius * 0.9, radius * 0.02);
}
function drawHand(pos, length, width) {
ctx.save();
ctx.rotate(pos);
ctx.beginPath();
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.moveTo(0, 0);
ctx.lineTo(0, -length);
ctx.stroke();
ctx.restore();
}
<!DOCTYPE html>
<html>
<body style="background-color: #009688">
<canvas
id="canvas"
width="240"
height="240"
style="background-color: transparent"
></canvas>
<p><button id="left" onclick="clockwise()">counter-clockwise</button></p>
<p><button id="right" onclick="counter()">clockwise</button></p>
</body>
</html>

最新更新