search
HomeWeb Front-endJS Tutorialcanvas dynamic ball overlapping effect

Previous words

In the javascript sports series, various sports are introduced in detail, including wall collision sports. However, if you use canvas to implement it, it is another way of thinking. This article will introduce in detail the overlapping effect of canvas dynamic balls

static balls

First, generate 50 static balls with random radius and random position

<button>按钮</button><canvas>当前浏览器不支持canvas,请更换浏览器后再试</canvas><script>var canvas = document.getElementById(&#39;canvas&#39;);var H=300,W=500;
btn.onclick = function(){
    getBalls();
}
getBalls();function getBalls(){
    canvas.height = H;    if(canvas.getContext){        var cxt = canvas.getContext(&#39;2d&#39;);        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 = &#39;rgb(&#39; + tempR + &#39;,&#39; + tempG + &#39;,&#39; + tempB + &#39;)&#39;;            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>

Random movement

Next, these 50 balls make random movements, and the movement status of the balls needs to be updated in conjunction with the timer. At this time, the above code needs to be rewritten

<button>更新</button><canvas>当前浏览器不支持canvas,请更换浏览器后再试</canvas><script>btn.onclick = function(){history.go();}var canvas = document.getElementById(&#39;canvas&#39;);//存储画布宽高var H=300,W=500;//存储小球个数var NUM = 50;//存储小球var balls = [];function getBalls(){    if(canvas.getContext){        var cxt = canvas.getContext(&#39;2d&#39;);        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 = &#39;rgb(&#39; + tempR + &#39;,&#39; + tempG + &#39;,&#39; + tempB + &#39;)&#39;;            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(&#39;2d&#39;);        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>

Block detection

Next, add the ball collision detection Function, when the ball hits the wall, it changes to the opposite direction

function bumpTest(ele){    //左侧
    if(ele.x = W - ele.r){
        ele.x = W - ele.r;
        ele.stepX = -ele.stepX;
    }    //上侧
    if(ele.y = H - ele.r){
        ele.y = H - ele.r;
        ele.stepY = -ele.stepY;
    }
}

<button>更新</button>
<canvas>当前浏览器不支持canvas,请更换浏览器后再试</canvas>
<script>btn.onclick = function(){history.go();}var canvas = document.getElementById(&#39;canvas&#39;);//存储画布宽高var H=300,W=500;//存储小球个数var NUM = 30;//存储小球var balls = [];function getBalls(){    if(canvas.getContext){        var cxt = canvas.getContext(&#39;2d&#39;);        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 = &#39;rgb(&#39; + tempR + &#39;,&#39; + tempG + &#39;,&#39; + tempB + &#39;)&#39;;            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(&#39;2d&#39;);        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>

Overlap effect

The composite attribute globalCompositeOperation of canvas indicates how the graphics drawn later are combined with the graphics drawn first. The attribute value is a string, and the possible values ​​are as follows:

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

Add the overlapping effect of the ball to 'xor', which is the final effect display

<button>变换</button>
<canvas>当前浏览器不支持canvas,请更换浏览器后再试</canvas>
<script>btn.onclick = function(){history.go();}var canvas = document.getElementById(&#39;canvas&#39;);//存储画布宽高var H=300,W=500;//存储小球个数var NUM = 30;//存储小球var balls = [];function getBalls(){    if(canvas.getContext){        var cxt = canvas.getContext(&#39;2d&#39;);        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 = &#39;rgb(&#39; + tempR + &#39;,&#39; + tempG + &#39;,&#39; + tempB + &#39;)&#39;;            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(&#39;2d&#39;);        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 = &#39;xor&#39;;
            cxt.closePath();
            cxt.fill();   
        }        
    }

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

More canvas For articles related to the dynamic ball overlapping effect, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function