codepen:https://codepen.io/mo-kong/pe...
很奇怪,point在执行clear后已经只有一个数组了,但是render绘制时还是2个...更奇怪的是在render的map断点时,执行一个循环后会直接出现全部图形,且跳出循环。
刚刚尝试在clear时改变canvas的宽高就成功清除了。
why??
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
<canvas width="500" height="500" style="border: solid 2px red">
</canvas>
<button onclick="clearAll()">清除</button>
<script type="text/javascript">
const canvas = document.querySelectorAll('canvas')[0];
const context = canvas.getContext('2d')
context.beginPath();
context.strokeStyle = 'blue';
point = [
[{
x: 10,
y: 10
}, {
x: 10,
y: 100
}, {
x: 100,
y: 100
}, {
x: 100,
y: 10
}],
[{
x: 30,
y: 30
}, {
x: 30,
y: 300
}, {
x: 300,
y: 300
}, {
x: 300,
y: 30
}]
]
function render() {
// 先清空,在读取历史坐标点
point.map(list => {
context.moveTo(list[0].x, list[0].y);
for (let i = 1; i < list.length; i++) {
let item = list[i];
context.lineTo(item.x, item.y);
// context.stroke();
}
context.closePath();
context.stroke();
})
}
render()
function clearAll() {
console.log(point)
point.pop();
// point.pop();
context.clearRect(0, 0, 500, 500);
console.log(point)
render()
}
</script>
</body>
</html>
https://developer.mozilla.org...
如果不调用 context.beginPath(); 那么说明你这 2 个正方形是同一个路径