Tips: When you see this prompt, it means that the current article has been migrated from the original emlog blog system. The publication time of the article is too long ago, and the formatting and content may not be complete. Please understand.
HTML5 Canvas - Ball Collision
Date: 2017-7-18 Views: 2465 Comments: 2
html5 is the core language of the World Wide Web, a standard general-purpose markup language under which is an application of Hypertext Markup Language ( HTML ), the fifth major revision of HTML.
Since 1999, HTML 4.01 has undergone many changes. Today, several elements in HTML 4.01 have been deprecated, and these elements have been removed or redefined in HTML5.
In order to better handle today's Internet applications, HTML5 has added many new elements and features, such as: graphics drawing, multimedia content, better page structure, better form handling, and several APIs including drag-and-drop elements, geolocation, web application caching, storage, service workers, etc.
Tag
|
Description
|
---|---|
<canvas>
|
The tag defines graphics, such as charts and other images. This tag is based on the JavaScript drawing API.
|
Display effect:
Your browser does not support HTML5. Code section:
<canvas id="my-canvas" width="500px" height="400px" style="border:1px solid red" >Your browser does not support HTML5.</canvas>
<script type="text/javascript">
<!-- Get the canvas object -->
var my_canvas = document.getElementById("my-canvas");
<!-- Get the pen -->
var my_huabi = my_canvas.getContext("2d");
var x = 50;
var y = 50;
var r = 20;
function deawBall(x,y){
<!-- Set the pen color -->
my_huabi.fillStyle = "green";
<!-- Start a new path -->
my_huabi.beginPath();
<!-- Draw the ball -->
my_huabi.arc(x, y, r, 0, 2 * Math.PI);
<!-- Close the path -->
my_huabi.fill();
}
var fx_x = true;//When fx_x is true, move towards the x-axis
var fx_y = true;//When fx_y is true, move towards the y-axis
var speen = 1;
<!-- Timer -->
window.setInterval("moveBall()", 10);
function moveBall(){
<!-- Determine the current direction of the ball -->
if(fx_x == true){
x += speen;
if(x >= 500-r){
<!-- When reaching the bottom, bounce upwards -->
fx_x = false;
}
}else{
x -= speen;
if(x <= 0+r){
<!-- When reaching the top, bounce downwards -->
fx_x = true;
}
}
if(fx_y == true){
y += speen;
if(y >= 400-r){
<!-- When reaching the left side, bounce to the right side -->
fx_y = false;
}
}else{
y -= speen;
if(y <= 0+r){
<!-- When reaching the right side, bounce to the left side -->
fx_y = true;
}
}
<!-- Clear the canvas and redraw -->
my_huabi.clearRect(0, 0, 500, 400);
deawBall(x, y);
}
</script>
User Comments:
bandwagonhost 3 years ago (2017-08-15)
Friend, do you want to exchange links?阿珏 3 years ago (2017-08-16)
@bandwagonhost: You can apply for it on the friendly links application page.