最终结果如下
HTML代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> 点击页面上的任意位置,根据具体的坐标,生成一个圆 </title>
</head>
<body>
<canvas id="second">画布</canvas>
<script>
// 需要设置 画布的宽度以及高度为当前窗口的宽度与高度
let can = document.querySelector("#second");
can.width = window.innerWidth;
can.height = window.innerHeight;
let body = document.querySelector("html");
// 通过事件监听器向 指定的元素添加事件
body.addEventListener("click", function(e) {
// 此时 获取到中心坐标
let x = e.clientX;
let y = e.clientY;
drawCicle(x, y);
});
function drawCicle(x, y) {
console.log(x, y);
let can = document.querySelector("#second");
let ctx = can.getContext("2d");
ctx.beginPath();
let radius = 75;
let startAngle = 0;
let endAngle = 360;
ctx.arc(x, y, radius, startAngle, endAngle);
ctx.stroke();
}
</script>
</body>
</html>