使图像在其他图像html / JS范围内时消失

时间:2019-10-16 15:25:00

标签: javascript html canvas

以下代码能够显示2张图像:“ sac.gif”,“ ghost.png”。

“ ghost.jpg”是显示在画布上的对象,其具有由math.random确定的随机坐标。 “ sac.gif”是画布上的另一个对象,但具有动画效果,可以使用箭头键进行控制。

现在,该代码可以使用“ sac.gif”(其中的“ sac.gif”可以使用键盘控制)在画布上的随机区域中显示3个幻影。问题是我要添加的功能是在“ sac.gif”范围内时,幻影图像消失,而且我不太确定我该怎么做。

如果仍然有混淆,这里是我尝试重新创建的程序类型的链接。 http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  <link rel="stylesheet" href="Jeu.css">
  </head>
  <body>

    <canvas id="canvas" width="400" height="400"
    style="border-color: 'black'; border-width: 3px; border-style: solid">
      </canvas>
      <br>
        <button type="button"onclick="reset()"><img src="start.jpg"></button>
<script type="text/javascript">


window.requestAnimFrame = (function() {
  return window.requestAnimationFrame || 
    window.webkitRequestAnimationFrame || 
    window.mozRequestAnimationFrame || 
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame || 
    function(callback) {
      window.setTimeout(callback, 1000 / 60);

  };
})();

window.onload = function() {
var canvas = document.getElementById("canvas");
var contexte = canvas.getContext("2d");

var T_fleche_gauche = 37;
var T_fleche_droite = 39;
var T_fleche_haut = 38;
var T_fleche_bas = 40;

var player = {
    img: new Image();
  };
var x = 100;
  var y = 100;"
  var  w = 64;
  var  h = 64;
  var dx = 0;
  var dy = 0;

  player.img.src = "sac.gif"

  document.onkeydown = function(e) {
  toucheCourante = e.keyCode;

  if (toucheCourante == T_fleche_gauche) {
   dx = -1;
   dy = 0;
}
  if (toucheCourante == T_fleche_droite) {
       dx = 1;
       dy = 0;
    }
    if (toucheCourante == T_fleche_haut) {
       dy = -1;
       dx = 0;
    }
    if (toucheCourante == T_fleche_bas) {
       dy = 1;
      dx = 0;
    }
  }

function dessiner(x, y) {
      var random = function() {
      return {
        x: w + (Math.random() * (400 - (2*w))),
        y: h + (Math.random() * (400 - (2*h)))
      }
    };
  var points = [];
    for (var i = 0; i < x; i++) {
      points.push( random() );
    }
    return points;
  };
var ghost = {
    img: new Image(),
    };
ghost.img.src = "ghost.png";

function affiche(x,y) {
   for (var u of ghost.list) {
     contexte.drawImage(ghost.img, u.x, u.y, 50, 60);
   }
 }

  ghost.list  = dessiner(3, ghost);



    function draw() {
    contexte.save();
    contexte.clearRect(0, 0, 400, 400);
    contexte.translate(10+2*x,10+2*y);
    contexte.drawImage(player.img, x,y,70,90);
    contexte.restore();

    x = x+dx;
    y = y+dy;

    if (x > 125) x = -25;
    if (x < -25) x = 125;
    if (y > 125) y = -25;
    if (y < -25) y = 125;

    affiche();

    window.requestAnimFrame(function() {draw(dx,dy)});
  };

  draw(1,0);

};

function reset(){
location.reload()
}
  </script>
  </body>
</html>

0 个答案:

没有答案
相关问题