我正在尝试使用JavaScript绘制圆圈并在删除旧圆圈时重绘它。
我收到了这段代码:
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 15;
drawCircle(centerX,centerY,radius);
drawCircle(150,150,25);
function drawCircle(centerX,centerY,radius)
{
var canvas = document.getElementById('myCanvas');
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'black';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
};
</script>
问题是这两种方法绘制了两个圆而不是绘制一个圆而不是另一个圆。
我是JS的初学者,非常感谢帮助他们更好地绘制和删除圆圈
由于
答案 0 :(得分:0)
如果你想从画布中删除一个圆圈,你必须画一个圆圈(相同的位置;相同的大小),但这次是画布背景的颜色。
drawCircle(150,150,25,'black');
// ...
drawCircle(150,150,25,'white'); // removes previous circle if the canvas was white colored
如果你想在绘制新东西之前擦除画布上的所有东西,你可以执行这个
context.clearRect(0, 0, canvas.width, canvas.height);
答案 1 :(得分:0)
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 15;
function drawCircle(centerX,centerY,radius)
{
// Erase context
context.clearRect(0,0,canvas.width,canvas.height);
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'black';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
};
drawCircle(centerX,centerY,radius);
drawCircle(150,150,25);
&#13;
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
&#13;