我在html画布上创建游戏时遇到了麻烦。游戏的前提是你必须在它们撞到地面之前抓住气球。我对画布的背景有问题,并且篮子没有用鼠标移动。
背景应为黑色,篮子应该跟随鼠标光标。
https://jsfiddle.net/pgkL09j7/8/
<html>
<head>
<title>Sean Coyne</title>
<link rel="stylesheet" type="text/css" href="home.css">
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body onload="start_game()">
<body>
<section>
<article>
<div id="logo"><img src="LogoComic.png" id="Logo"></div><br></br>
<div id="canvas">
<canvas id="c" style="border:5px solid orange" height="500" width="500"></canvas>
<p id="p1"></p>
<script>
var balloon_x=100;
var balloon_y=0;
var basket_x=100;
var basket_y=100;
var points=0;
//Background colour of canvas
var c = document.getElementById("c");
var ctx = c.getContext("2d");
ctx.fillStyle = "#000";
ctx.fillRect(0,0,500,500);
//Here is the event listener
mycanv.addEventListener("mousemove",seenmotion, false);
function seenmotion(e) {
//This is the code for the mouse
//moving over the canvas.
var bounding_box=c.getBoundingClientRect();
basket_x=(e.clientX-bounding_box.left) *
(c.width/bounding_box.width);
basket_y=(e.clientY-bounding_box.top) *
(c.height/bounding_box.height);
}
function start_game() {
setInterval(game_loop, 50);
}
function game_loop() {
// The code above is called every 50ms and is a
// frame-redraw-game-animation loop.
c.width = c.width;
// Below is the code that draws the objects
draw_balloon(balloon_x,balloon_y);
draw_basket(basket_x,basket_y);
// Below is the code that updates the balloons location
balloon_x++;
if (balloon_x>c.width) {
balloon_x=0;
}
//Here is the collision detection code
if (collision(balloon_x, balloon_y, basket_x, basket_y)) {
points -= 0.5;
}
//Here is the code for the point system
points+=1;
// and let's stick it in the top right.
var integerpoints=Math.floor(points); // make it into an integer
ctx.font="bold 24px sans-serif ";
ctx.fillText(integerpoints, c.width-50, 50);
}
context.clearRect ( 0 , 0 , 500, 500 );
function collision(basket_x, basket_y, ball_x, ball_y) {
if(balloon_y + 85 < basket_y) {
return false;
}
if (balloon_y > basket_y + 91) {
return false;
}
if (balloon_x + 80 < basket_x) {
return false;
}
if (balloon_x > basket_x + 80) {
return false;
}
return true;
}
// Code to stop the game when we're finished playing
function stop_game() {
}
//Code for the ball
function draw_balloon(x,y) {
var balloon_img=new Image();
balloon_img.src="balloon.png";
ctx.drawImage(balloon_img,x,y);
}
//Code for the basket
function draw_basket(x,y) {
var basket_img=new Image();
basket_img.src="basket.png";
ctx.drawImage(basket_img,x,y);
}
</script>
</div>
</article>
</section>
</body>
</html>
答案 0 :(得分:0)
您必须更改mouselistener的变量。而不是
mycanv.addEventListener("mousemove",seenmotion, false);
你必须写这个
c.addEventListener("mousemove",seenmotion, false);
用鼠标移动篮子,但图像仍然不对。您必须从x和y坐标中减去图像宽度和高度的一半。 要修复背景,您必须修改CSS。文章和部分标签都有全宽/高和自己的背景。这不应该难以解决,只需将#c的背景更改为黑色。
#c {
background-color: black;
}
这是jsfiddle:https://jsfiddle.net/pgkL09j7/10/
访问http://www.w3schools.com/以获取有关CSS和JS的更多信息。此外,代码可以更容易和更有条理。