再現できません.コード全てを見せてください.
HTML
1<!DOCTYPE html>
2<meta charset="UTF-8">
3<title>Example</title>
4<canvas></canvas>
5<script>
6 'use strict';
7
8 addEventListener('DOMContentLoaded', () => {
9 let canvas = document.querySelector('canvas');
10 let ctx = canvas.getContext('2d');
11 function fitsize() {
12 canvas.width = window.innerWidth;
13 canvas.height = window.innerHeight;
14 }
15 addEventListener('resize', fitsize);
16 fitsize();
17
18 let x = 0, y = 0, radius = 50, vx = 2, vy = 2, cnt = 0;
19 let timer = setInterval(() => {
20 ++cnt;
21 ctx.clearRect(0, 0, canvas.width, canvas.height);
22 ctx.beginPath();
23 if (x + 2 * radius > canvas.width || x < 0) vx = -vx;
24 if (y + 2 * radius > canvas.height || y < 0) vy = -vy;
25 x += vx;
26 y += vy;
27 ctx.arc(x + radius, y + radius, radius, 0, Math.PI * 2);
28 ctx.fillStyle = 'red';
29 ctx.fill();
30 if (cnt == 100) {
31 clearInterval(timer);
32 }
33 });
34 });
35</script>
これはちゃんと一定時間後に止まりますし,
HTML
1<!DOCTYPE html>
2<meta charset="UTF-8">
3<title>Example</title>
4<canvas></canvas>
5<script>
6 'use strict';
7
8 addEventListener('DOMContentLoaded', () => {
9 let canvas = document.querySelector('canvas');
10 let ctx = canvas.getContext('2d');
11 function fitsize() {
12 canvas.width = window.innerWidth;
13 canvas.height = window.innerHeight;
14 }
15 addEventListener('resize', fitsize);
16 fitsize();
17
18 let x = 0, y = 0, radius = 50, vx = 2, vy = 2, cnt = 0;
19 let timer = setInterval(() => {
20 ++cnt;
21 ctx.clearRect(0, 0, canvas.width, canvas.height);
22 ctx.beginPath();
23 if (x + 2 * radius > canvas.width || x < 0) vx = -vx;
24 if (y + 2 * radius > canvas.height || y < 0) vy = -vy;
25 x += vx;
26 y += vy;
27 ctx.arc(x + radius, y + radius, radius, 0, Math.PI * 2);
28 ctx.fillStyle = 'red';
29 ctx.fill();
30 });
31
32 if (cnt == 100) {
33 clearInterval(timer);
34 }
35 });
36</script>
こっちは動き続けます.
なおこのようなアニメーション用途では,(ブラウザの対応がまちまちですが)requestAnimationFrame
を使うほうがおすすめです.
HTML
1<!DOCTYPE html>
2<meta charset="UTF-8">
3<title>Example</title>
4<canvas></canvas>
5<script>
6 'use strict';
7
8 addEventListener('DOMContentLoaded', () => {
9 let canvas = document.querySelector('canvas');
10 let ctx = canvas.getContext('2d');
11 function fitsize() {
12 canvas.width = window.innerWidth;
13 canvas.height = window.innerHeight;
14 }
15 addEventListener('resize', fitsize);
16 fitsize();
17
18 let x = 0, y = 0, radius = 50, vx = 2, vy = 2;
19 requestAnimationFrame(function draw() {
20 requestAnimationFrame(draw);
21 ctx.clearRect(0, 0, canvas.width, canvas.height);
22 ctx.beginPath();
23 if (x + 2 * radius > canvas.width || x < 0) vx = -vx;
24 if (y + 2 * radius > canvas.height || y < 0) vy = -vy;
25 x += vx;
26 y += vy;
27 ctx.arc(x + radius, y + radius, radius, 0, Math.PI * 2);
28 ctx.fillStyle = 'red';
29 ctx.fill();
30 });
31 });
32</script>