Jscript animation series (1) -- draw a small ball on Canvas with JS

Posted by jazz_snob on Sun, 22 Dec 2019 22:49:08 +0100

Recently in the study of JS animation, have some heart to share with you! Due to the lack of content in the early stage, the styles and other things are written in the Html file!

First (Index.html)

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title>this is one Ball</title>
	</head>
	<body>
		<canvas id="canvas" width="400" height="400"style="background-color:#000></canvas>
		<script src="Ball.js"></script>
		<script>
			window.onload=function(){
				//Our code here...
			};
		</script>
	</body>
</html>

The above Html code is equivalent to a template, which will not change much. The main content is in the < srcipt > tag.

Next, we will create a JS file. This file is mainly a ball class. This class has some attributes of the ball, such as radius, color, position (x,y), and other methods.

Filename (Ball.js)

//Define a Ball
function Ball (radius,color){
	if(radius === undefined){radius=40;}
	if(color === undefined){color="#ff0000";}
	this.x=0;//x-coordinate 
	this.y=0;//y coordinate
	this.radius=radius;//radius
	this.vx = 0;
	this.vy = 0;
	this.rotation=0;//Rotation angle
	this.color=color;//utils.parseColor(color);
	this.lineWidth=1;
}
//Drawing method of small ball
Ball.prototype.draw=function(context){
	context.save();//First save the current canvas status
	context.translate(this.x,this.y); //Set coordinate origin to (x,y), default
	context.rotate(this.rotation); //Rotate current drawing
	context.lineWidth=this.lineWidth; //Brush thickness
	context.fillStyle=this.color;  //Color filled in circle
	context.beginPath();  //Start a painting path
	context.arc(0,0,this.radius,0,(Math.PI*2),true); //Draw a circle
	context.closePath();  //End current path
	context.fill();  //Start filling
	//If there is a border
	if(this.lineWidth>0){
		context.stroke(); //bound box
	}
	context.restore();//Sets the drawing state to a saved value.
};

explain:

  1. Note is only a brief explanation, if you want to know more about Baidu.
  2. The Ball.js file can be saved separately when you want to use < script SRC = "ball. JS" >
  3. Now it's just the simplest circle, and some other attributes and methods will be added later, such as (speed attribute, density attribute, luminous effect), etc.

Now let's start writing the contents of < script >

window.onload=function(){
	var canvas = document.getElementById('canvas');
		context = canvas.getContext('2d');
	var ball=new Ball();  //Create a Ball
        ball.x=canvas.width/2;  //Set its position (center of canvas)
        ball.y=canvas.height/2;
	ball.draw(context);  //Call Ball's draw method
};

So it's very easy to draw a circle on canvas;

 

 

 

 

 

 

 

 

 

 

 

Topics: Attribute