前提
canvasの背景アニメーションを作成しているのですが思った挙動にならず苦戦しています。
実現したいこと
https://codepen.io/smpnjn/pen/yLPdEPQ
上記のページのような円同士がが近づくとアメーバのように引き寄せあって合体するような挙動を実現したいです
*ピントがあったり合わなかったりの挙動は不要です。
発生している問題・エラーメッセージ
バウンドする挙動までは実現できたのですが
これに他のアニメーションを組み込む方法がわからずじまいになっています。
試したこと
/* * グローバル変数 */ let wrapper = null; // キャンバスの親要素 let canvas = null; // キャンバス let g = null; // コンテキスト let $id = function(id){ return document.getElementById(id); }; // DOM取得用 const speed1 = -0.8; let balls = []; /* * キャンバスのサイズをウインドウに合わせて変更 */ function getSize(){ // キャンバスのサイズを再設定 canvas.width = wrapper.offsetWidth; canvas.height = wrapper.offsetHeight; balls.forEach(ball => ball.r = canvas.width/8); } // ボール1 let ball1 = { x: 160, y: 500, vx: speed1, vy: speed1, color: "steelblue", }; // ボール2 let ball2 = { x: 200, y: 220, vx: speed1, vy: speed1, color: "steelblue", }; // ボール2 let ball3 = { x: 500, y: 220, vx: speed1, vy: speed1, color: "steelblue", }; let ball4 = { x: 500, y: 600, vx: speed1, vy: speed1, color: "steelblue", }; let ball5 = { x: 800, y: 600, vx: speed1, vy: speed1, color: "steelblue", }; //let x, y, r; // ●のx座標、y座標、半径 //let vx, vy; // x方向の速度、y方向の速度 function drawAnim(){ // 背景をグレーに g.fillStyle = "rgb( 255, 255, 255)"; g.fillRect(0, 0, canvas.width, canvas.height); // ballを描画 for(let ball of balls){ g.beginPath(); g.fillStyle = ball.color; // 塗りつぶす色 g.arc(ball.x, ball.y, ball.r, 0, Math.PI*2, false); g.fill(); // ●の移動 ball.x += ball.vx; ball.y += ball.vy; // 壁に当たったら跳ね返る(●のxy座標は中心点のため、半径を考慮) if(ball.x < 0+ball.r || ball.x > canvas.width-ball.r){ ball.vx = -ball.vx; } if(ball.y < 0+ball.r || ball.y > canvas.height-ball.r){ ball.vy = -ball.vy; } } // 再帰呼び出しでアニメーションさせる requestAnimationFrame(drawAnim); } window.addEventListener("load", function(){ // キャンバスの親要素情報取得(親要素が無いとキャンバスのサイズが画面いっぱいに表示できないため) wrapper = $id("wrapper"); // キャンバス情報取得 canvas = $id("canvas"); g = canvas.getContext("2d"); balls.push(ball1); balls.push(ball2); balls.push(ball3); balls.push(ball4); balls.push(ball5); // アニメーション開始 drawAnim(); // キャンバスをウインドウサイズにする getSize(); }); /* * リサイズ時 */ window.addEventListener("resize", function(){ getSize(); });

あなたの回答
tips
プレビュー