慕姐8450365
qq_天冷团成球_0
已解决

慕函数5127544
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Canvas绘图详解 16</title>
<style>
canvas {
border: 1px solid #aaa;
display: block;
margin: 50px auto;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="800">不好意思,您的浏览器不支持canvas。</canvas>
<script type="text/javascript">
var balls = [];
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
window.onload = function() {
for (var i = 0; i < 10; i++) {
var ball = {
x: Math.random() * 800,
y: Math.random() * 800,
r: Math.random() * 50 + 20
};
balls[i] = ball;
}
canvas.addEventListener("mousemove", detect);
};
function draw(x, y) {
for (var i = 0; i < balls.length; i++) {
ctx.beginPath();
ctx.arc(balls[i].x, balls[i].y, balls[i].r, 0, Math.PI * 2);
if (ctx.isPointInPath(x, y)) {
ctx.fillStyle = "#ff0000";
} else {
ctx.fillStyle = "#058";
}
ctx.fill();
}
}
function detect(e) {
var x = e.clientX - canvas.getBoundingClientRect().left;
var y = e.clientY - canvas.getBoundingClientRect().top;
draw(x, y);
}
</script>
</body>
</html>
koyil
不行的,因为重画效率也很高
厉害Sin
差别大了,前者指元素(比如某个div)距离可视区域顶部的距离,后者包括滚动条卷起的部分。

js原生的offsetTop属性有很多浏览器兼容性问题,用时要慎重。
hhhs1s1s
2222
灯元
这个代码,你写错了,这儿应该是y, var y=event.clientY-canvas.getBoundingClientRect().top;
身披金甲圣衣的一条狗
坐标参数是一个点
mikeding
看到了。。。。。。。
qq_lzY
四个错误:
第44行,getBoundingClientRect()拼写错误,“bound”的b是大写的
detect和draw函数的for循环条件多了个“=”
第48行beginPath拼写错误
第54行的括号后面有个多余的符号。
这些错误在浏览器上调试调试就可以发现问题的。
Betsey
if(c.isPointInPath(x,y)) 这个判断应该在for循环里面
aimeeWu
不可以,offset相对定位父级元素
用户1155536
你能不能在具体点,有代码吗
979103157
canvas不需要引用JS文件,但是需要浏览器支持
979103157
Toyopo
你用bezierCurveTo画的多复杂的图形都能用closePath方法闭合
鼠标点击可以获取x y坐标
通过context.isPointInPath这个方法来进行判断啊
曜曜OvO