canvas动态小球重叠效果

前面的话

  在javascript运动系列中,详细介绍了各种运动,其中就包括碰壁运动。但是,如果用canvas去实现,却是另一种思路。本文将详细介绍canvas动态小球重叠效果

 

效果展示

静态小球

  首先,生成随机半径、随机位置的50个静态小球

<button id="btn">按钮</button>
<canvas id="canvas" width="500" height="300" style="border:1px solid black">当前浏览器不支持canvas,请更换浏览器后再试</canvas>
<script>
var canvas = document.getElementById('canvas');
var H=300,W=500;
btn.onclick = function(){
    getBalls();
}
getBalls();
function getBalls(){
    canvas.height = H;
    if(canvas.getContext){
        var cxt = canvas.getContext('2d');
        for(var i = 0; i < 50; i++){
            var tempR = Math.floor(Math.random()*255);
            var tempG = Math.floor(Math.random()*255);
            var tempB = Math.floor(Math.random()*255);
            cxt.fillStyle = 'rgb(' + tempR + ',' + tempG + ',' + tempB + ')';
            var tempW = Math.floor(Math.random()*W);
            var tempH = Math.floor(Math.random()*H);
            var tempR = Math.floor(Math.random()*50);
            cxt.beginPath();
            cxt.arc(tempW,tempH,tempR,0,Math.PI*2);
            cxt.fill();
        }
    }    
}
</script>    

随机运动

  接着,这50个小球做随机运动,需要配合定时器更新小球的运动状态。这时,需要对上面代码进行改写

<button id="btn">更新</button>
<canvas id="canvas" width="500" height="300" style="border:1px solid black">当前浏览器不支持canvas,请更换浏览器后再试</canvas>
<script>
btn.onclick = function(){history.go();}
var canvas = document.getElementById('canvas');
//存储画布宽高
var H=300,W=500;
//存储小球个数
var NUM = 50;
//存储小球
var balls = [];
function getBalls(){
    if(canvas.getContext){
        var cxt = canvas.getContext('2d');
        for(var i = 0; i < NUM; i++){
            var tempR = Math.floor(Math.random()*255);
            var tempG = Math.floor(Math.random()*255);
            var tempB = Math.floor(Math.random()*255);
            var tempColor = 'rgb(' + tempR + ',' + tempG + ',' + tempB + ')';
            var tempX = Math.floor(Math.random()*W);
            var tempY = Math.floor(Math.random()*H);
            var tempR = Math.floor(Math.random()*30+20);
            var tempBall = {
                x:tempX,
                y:tempY,
                r:tempR,
                stepX:Math.floor(Math.random() * 4 -2),
                stepY:Math.floor(Math.random() * 4 -2),
                color:tempColor,
                disX:Math.floor(Math.random() * 3 -1),
                disY:Math.floor(Math.random() * 3 -1)
            };
            balls.push(tempBall);
        }
    }    
}
function updateBalls(){
    for(var i = 0; i < balls.length; i++){
        balls[i].stepY += balls[i].disY;
        balls[i].stepX += balls[i].disX;
        balls[i].x += balls[i].stepX;
        balls[i].y += balls[i].stepY;                 
    }
}

function renderBalls(){
    //重置画布高度,达到清空画布的效果
    canvas.height = H;    
    if(canvas.getContext){
        var cxt = canvas.getContext('2d');
        for(var i = 0; i < balls.length; i++){
            cxt.beginPath();
            cxt.arc(balls[i].x,balls[i].y,balls[i].r,0,2*Math.PI);
            cxt.fillStyle = balls[i].color;
            cxt.closePath();
            cxt.fill();   
        }        
    }

}
getBalls();
clearInterval(oTimer);
var oTimer = setInterval(function(){
    //更新小球运动状态
    updateBalls();
    //渲染小球
    renderBalls();
},50);
</script>

碰壁检测

  下面,增加小球的碰壁检测功能,当小球碰壁时,变为相反方向

function bumpTest(ele){
    //左侧
    if(ele.x <= ele.r){
        ele.x = ele.r;
        ele.stepX = -ele.stepX;
    }
    //右侧
    if(ele.x >= W - ele.r){
        ele.x = W - ele.r;
        ele.stepX = -ele.stepX;
    }
    //上侧
    if(ele.y <= ele.r){
        ele.y = ele.r;
        ele.stepY = -ele.stepY;
    }
    //下侧
    if(ele.y >= H - ele.r){
        ele.y = H - ele.r;
        ele.stepY = -ele.stepY;
    }
}
<button >更新</button>
<canvas  width="500" height="300" style="border:1px solid black">当前浏览器不支持canvas,请更换浏览器后再试</canvas>
<script>
btn.onclick = function(){history.go();}
var canvas = document.getElementById('canvas');
//存储画布宽高
var H=300,W=500;
//存储小球个数
var NUM = 30;
//存储小球
var balls = [];
function getBalls(){
    if(canvas.getContext){
        var cxt = canvas.getContext('2d');
        for(var i = 0; i < NUM; i++){
            var tempR = Math.floor(Math.random()*255);
            var tempG = Math.floor(Math.random()*255);
            var tempB = Math.floor(Math.random()*255);
            var tempColor = 'rgb(' + tempR + ',' + tempG + ',' + tempB + ')';
            var tempR = Math.floor(Math.random()*30+20);
            var tempX = Math.floor(Math.random()*(W-tempR) + tempR);
            var tempY = Math.floor(Math.random()*(H-tempR) + tempR);
            
            var tempBall = {
                x:tempX,
                y:tempY,
                r:tempR,
                stepX:Math.floor(Math.random() * 13 -6),
                stepY:Math.floor(Math.random() * 13 -6),
                color:tempColor
            };
            balls.push(tempBall);
        }
    }    
}
function updateBalls(){
    for(var i = 0; i < balls.length; i++){
        balls[i].x += balls[i].stepX;
        balls[i].y += balls[i].stepY; 
        bumpTest(balls[i]);
    }
}
function bumpTest(ele){
    //左侧
    if(ele.x <= ele.r){
        ele.x = ele.r;
        ele.stepX = -ele.stepX;
    }
    //右侧
    if(ele.x >= W - ele.r){
        ele.x = W - ele.r;
        ele.stepX = -ele.stepX;
    }
    //上侧
    if(ele.y <= ele.r){
        ele.y = ele.r;
        ele.stepY = -ele.stepY;
    }
    //下侧
    if(ele.y >= H - ele.r){
        ele.y = H - ele.r;
        ele.stepY = -ele.stepY;
    }
}
function renderBalls(){
    //重置画布高度,达到清空画布的效果
    canvas.height = H;    
    if(canvas.getContext){
        var cxt = canvas.getContext('2d');
        for(var i = 0; i < balls.length; i++){
            cxt.beginPath();
            cxt.arc(balls[i].x,balls[i].y,balls[i].r,0,2*Math.PI);
            cxt.fillStyle = balls[i].color;
            cxt.closePath();
            cxt.fill();   
        }        
    }

}
getBalls();
clearInterval(oTimer);
var oTimer = setInterval(function(){
    //更新小球运动状态
    updateBalls();
    //渲染小球
    renderBalls();
},50);
</script>    

重叠效果

  canvas的合成属性globalCompositeOperation表示后绘制的图形怎样与先绘制的图形结合,属性值是字符串,可能值如下:

source-over(默认):后绘制的图形位于先绘制的图形上方
source-in:后绘制的图形与先绘制的图形重叠的部分可见,两者其他部分完全透明
source-out:后绘制的图形与先绘制的图形不重叠的部分可见,先绘制的图形完全透明
source-atop:后绘制的图形与先绘制的图形重叠的部分可见,先绘制的图形不受影响
destination-over:后绘制的图形位于先绘制的图形下方,只有之前透明像素下的部分才可见
destination-in:后绘制的图形位于先绘制的图形下方,两者不重叠的部分完全透明
destination-out:后绘制的图形擦除与先绘制的图形重叠的部分
destination-atop:后绘制的图形位于先绘制的图形下方,在两者不重叠的地方,先绘制的图形会变透明
lighter:后绘制的图形与先绘制的图形重叠部分的值相加,使该部分变亮
copy:后绘制的图形完全替代与之重叠的先绘制图形 
xor:后绘制的图形与先绘制的图形重叠的部分执行"异或"操作

  增加小球的重叠效果为'xor',即为最终的效果展示 

<button >变换</button>
<canvas  width="500" height="300" style="border:1px solid black">当前浏览器不支持canvas,请更换浏览器后再试</canvas>
<script>
btn.onclick = function(){history.go();}
var canvas = document.getElementById('canvas');
//存储画布宽高
var H=300,W=500;
//存储小球个数
var NUM = 30;
//存储小球
var balls = [];
function getBalls(){
    if(canvas.getContext){
        var cxt = canvas.getContext('2d');
        for(var i = 0; i < NUM; i++){
            var tempR = Math.floor(Math.random()*255);
            var tempG = Math.floor(Math.random()*255);
            var tempB = Math.floor(Math.random()*255);
            var tempColor = 'rgb(' + tempR + ',' + tempG + ',' + tempB + ')';
            var tempR = Math.floor(Math.random()*30+20);
            var tempX = Math.floor(Math.random()*(W-tempR) + tempR);
            var tempY = Math.floor(Math.random()*(H-tempR) + tempR);
            
            var tempBall = {
                x:tempX,
                y:tempY,
                r:tempR,
                stepX:Math.floor(Math.random() * 21 -10),
                stepY:Math.floor(Math.random() * 21 -10),
                color:tempColor
            };
            balls.push(tempBall);
        }
    }    
}
function updateBalls(){
    for(var i = 0; i < balls.length; i++){
        balls[i].x += balls[i].stepX;
        balls[i].y += balls[i].stepY; 
        bumpTest(balls[i]);
    }
}
function bumpTest(ele){
    //左侧
    if(ele.x <= ele.r){
        ele.x = ele.r;
        ele.stepX = -ele.stepX;
    }
    //右侧
    if(ele.x >= W - ele.r){
        ele.x = W - ele.r;
        ele.stepX = -ele.stepX;
    }
    //上侧
    if(ele.y <= ele.r){
        ele.y = ele.r;
        ele.stepY = -ele.stepY;
    }
    //下侧
    if(ele.y >= H - ele.r){
        ele.y = H - ele.r;
        ele.stepY = -ele.stepY;
    }
}
function renderBalls(){
    //重置画布高度,达到清空画布的效果
    canvas.height = H;    
    if(canvas.getContext){
        var cxt = canvas.getContext('2d');
        for(var i = 0; i < balls.length; i++){
            cxt.beginPath();
            cxt.arc(balls[i].x,balls[i].y,balls[i].r,0,2*Math.PI);
            cxt.fillStyle = balls[i].color;
            cxt.globalCompositeOperation = 'xor';
            cxt.closePath();
            cxt.fill();   
        }        
    }

}
getBalls();
clearInterval(oTimer);
var oTimer = setInterval(function(){
    //更新小球运动状态
    updateBalls();
    //渲染小球
    renderBalls();
},50);
</script>    

源码查看

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现动态碰撞需要用到Canvas的2D绘图API,具体步骤如下: 1. 创建Canvas元素和2D绘图上下文 ```html <canvas id="canvas"></canvas> ``` ```javascript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ``` 2. 定义小对象 ```javascript class Ball { constructor(x, y, r, vx, vy, color) { this.x = x; // 圆心x坐标 this.y = y; // 圆心y坐标 this.r = r; // 半径 this.vx = vx; // 水平速度 this.vy = vy; // 垂直速度 this.color = color; // 颜色 } draw() { ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); } } ``` 3. 创建多个小对象,并绘制到Canvas上 ```javascript const balls = []; // 存储小对象的数组 const colors = ['#ff0000', '#00ff00', '#0000ff']; // 小颜色 for (let i = 0; i < 3; i++) { const ball = new Ball( Math.random() * canvas.width, // 随机x坐标 Math.random() * canvas.height, // 随机y坐标 20, // 半径 Math.random() * 4 - 2, // 随机水平速度 Math.random() * 4 - 2, // 随机垂直速度 colors[i] // 随机颜色 ); balls.push(ball); } function drawBalls() { balls.forEach(ball => ball.draw()); } drawBalls(); ``` 4. 实现小碰撞 ```javascript function updateBalls() { balls.forEach(ball => { ball.x += ball.vx; ball.y += ball.vy; // 碰到边界反弹 if (ball.x < ball.r || ball.x > canvas.width - ball.r) { ball.vx = -ball.vx; } if (ball.y < ball.r || ball.y > canvas.height - ball.r) { ball.vy = -ball.vy; } // 碰撞检测 balls.forEach(otherBall => { if (ball !== otherBall) { const dx = ball.x - otherBall.x; const dy = ball.y - otherBall.y; const distance = Math.sqrt(dx * dx + dy * dy); if (distance < ball.r + otherBall.r) { // 碰撞 const angle = Math.atan2(dy, dx); const sin = Math.sin(angle); const cos = Math.cos(angle); // 旋转坐标系 const x1 = 0; const y1 = 0; const x2 = dx * cos + dy * sin; const y2 = dy * cos - dx * sin; // 旋转速度向量 const vx1 = ball.vx * cos + ball.vy * sin; const vy1 = ball.vy * cos - ball.vx * sin; const vx2 = otherBall.vx * cos + otherBall.vy * sin; const vy2 = otherBall.vy * cos - otherBall.vx * sin; // 碰撞后的速度向量 const vx1Final = ((ball.r - otherBall.r) * vx1 + 2 * otherBall.r * vx2) / (ball.r + otherBall.r); const vx2Final = ((otherBall.r - ball.r) * vx2 + 2 * ball.r * vx1) / (ball.r + otherBall.r); const vy1Final = vy1; const vy2Final = vy2; // 旋转回原坐标系 const x1Final = x1 * cos - y1 * sin; const y1Final = y1 * cos + x1 * sin; const x2Final = x2 * cos - y2 * sin; const y2Final = y2 * cos + x2 * sin; // 更新位置和速度向量 ball.x = ball.x + (x1Final - x1); ball.y = ball.y + (y1Final - y1); ball.vx = vx1Final * cos - vy1Final * sin; ball.vy = vy1Final * cos + vx1Final * sin; otherBall.x = ball.x + (x2Final - x1); otherBall.y = ball.y + (y2Final - y1); otherBall.vx = vx2Final * cos - vy2Final * sin; otherBall.vy = vy2Final * cos + vx2Final * sin; } } }); }); } ``` 5. 清空Canvas并更新小位置 ```javascript function clearCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); } function loop() { clearCanvas(); updateBalls(); drawBalls(); requestAnimationFrame(loop); } loop(); ``` 完整代码如下: ```html <canvas id="canvas"></canvas> ``` ```javascript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); class Ball { constructor(x, y, r, vx, vy, color) { this.x = x; // 圆心x坐标 this.y = y; // 圆心y坐标 this.r = r; // 半径 this.vx = vx; // 水平速度 this.vy = vy; // 垂直速度 this.color = color; // 颜色 } draw() { ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); } } const balls = []; // 存储小对象的数组 const colors = ['#ff0000', '#00ff00', '#0000ff']; // 小颜色 for (let i = 0; i < 3; i++) { const ball = new Ball( Math.random() * canvas.width, // 随机x坐标 Math.random() * canvas.height, // 随机y坐标 20, // 半径 Math.random() * 4 - 2, // 随机水平速度 Math.random() * 4 - 2, // 随机垂直速度 colors[i] // 随机颜色 ); balls.push(ball); } function drawBalls() { balls.forEach(ball => ball.draw()); } function updateBalls() { balls.forEach(ball => { ball.x += ball.vx; ball.y += ball.vy; // 碰到边界反弹 if (ball.x < ball.r || ball.x > canvas.width - ball.r) { ball.vx = -ball.vx; } if (ball.y < ball.r || ball.y > canvas.height - ball.r) { ball.vy = -ball.vy; } // 碰撞检测 balls.forEach(otherBall => { if (ball !== otherBall) { const dx = ball.x - otherBall.x; const dy = ball.y - otherBall.y; const distance = Math.sqrt(dx * dx + dy * dy); if (distance < ball.r + otherBall.r) { // 碰撞 const angle = Math.atan2(dy, dx); const sin = Math.sin(angle); const cos = Math.cos(angle); // 旋转坐标系 const x1 = 0; const y1 = 0; const x2 = dx * cos + dy * sin; const y2 = dy * cos - dx * sin; // 旋转速度向量 const vx1 = ball.vx * cos + ball.vy * sin; const vy1 = ball.vy * cos - ball.vx * sin; const vx2 = otherBall.vx * cos + otherBall.vy * sin; const vy2 = otherBall.vy * cos - otherBall.vx * sin; // 碰撞后的速度向量 const vx1Final = ((ball.r - otherBall.r) * vx1 + 2 * otherBall.r * vx2) / (ball.r + otherBall.r); const vx2Final = ((otherBall.r - ball.r) * vx2 + 2 * ball.r * vx1) / (ball.r + otherBall.r); const vy1Final = vy1; const vy2Final = vy2; // 旋转回原坐标系 const x1Final = x1 * cos - y1 * sin; const y1Final = y1 * cos + x1 * sin; const x2Final = x2 * cos - y2 * sin; const y2Final = y2 * cos + x2 * sin; // 更新位置和速度向量 ball.x = ball.x + (x1Final - x1); ball.y = ball.y + (y1Final - y1); ball.vx = vx1Final * cos - vy1Final * sin; ball.vy = vy1Final * cos + vx1Final * sin; otherBall.x = ball.x + (x2Final - x1); otherBall.y = ball.y + (y2Final - y1); otherBall.vx = vx2Final * cos - vy2Final * sin; otherBall.vy = vy2Final * cos + vx2Final * sin; } } }); }); } function clearCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); } function loop() { clearCanvas(); updateBalls(); drawBalls(); requestAnimationFrame(loop); } loop(); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值