I am making an animation of ball and paddle. Ball is bouncing well. After this i want a paddle or a <div>
element shaped "paddle" at x-axis. This paddle must be moving only by x-axis and should be moving when i active cursor at any position to x-axis. Any help?
Here is my code:
var x=150;
var y=150;
var dx=2;
var dy=4;
var WIDTH;
var HEIGHT;
var ctx=document.getElementById("canvas").getContext("2d");
ctx.beginPath();
ctx.arc(150,150,10,0,2*Math.PI,true);
ctx.closePath();
ctx.fill();
function init() {
var ctx=document.getElementById("canvas").getContext("2d");
return setInterval(draw,10);
}
function draw() {
ctx.clearRect(0,0,300,300);
ctx.beginPath();
ctx.arc(x,y,10,0,2*Math.PI,true);
ctx.closePath();
ctx.fill();
x+=dx;
y+=dy;
bounce();
}
function bounce(){
if(x+dx>300||x+dx<0)
dx=-dx;
if(y+dy>300||y+dy<0)
dy=-dy;
}
init();
Try this code:
In your var declarations:
var mouseX = 150;
In your init()
function:
document.getElementById("canvas").addEventListener('mousemove', moveHandler);
In your draw()
function:
ctx.rect(mouseX-20,280,40,5); // rect( x , y , width , height )
ctx.fillStyle = 'black'; // ^ This is the mouse's X position, minus half the paddle width.
ctx.fill();
And finally, add this function:
function moveHandler(e){
e = e || window.event; // Compatibility.
mouseX = e.offsetX;
}
So, your resulting code Will look like this :
var x=150;
var y=150;
var dx=2;
var dy=4;
var WIDTH;
var HEIGHT;
var mouseX = 150;
var mouseY;
var ctx=document.getElementById("canvas").getContext("2d");
ctx.beginPath();
ctx.arc(150,150,10,0,2*Math.PI,true);
ctx.closePath();
ctx.fill();
function init() {
document.getElementById("canvas").addEventListener('mousemove', moveHandler);
return setInterval(draw,10);
}
function moveHandler(e){
mouseX = e.offsetX;
}
function draw() {
ctx.clearRect(0,0,300,300);
ctx.rect(mouseX-20,280,40,5);
ctx.fillStyle = 'black';
ctx.fill();
ctx.beginPath();
ctx.arc(x,y,10,0,2*Math.PI,true);
ctx.closePath();
ctx.fill();
x+=dx;
y+=dy;
bounce();
}
function bounce(){
if(x+dx>300||x+dx<0)
dx=-dx;
if(y+dy>300||y+dy<0)
dy=-dy;
}
init();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.