[英]Want a paddle at bottom x-axis in this animation
我正在制作球和槳的動畫。 球彈跳良好。 在此之后,我想要在x軸上設置形狀為“ paddle”的槳或<div>
元素。 槳必須只能沿x軸移動,並且當我在x軸上的任何位置激活光標時,都應移動。 有什么幫助嗎?
這是我的代碼:
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();
試試這個代碼:
在您的var聲明中:
var mouseX = 150;
在您的init()
函數中:
document.getElementById("canvas").addEventListener('mousemove', moveHandler);
在您的draw()
函數中:
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();
最后,添加以下功能:
function moveHandler(e){
e = e || window.event; // Compatibility.
mouseX = e.offsetX;
}
因此,您得到的代碼將如下所示 :
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.