Анимированные квадратные подпрыгивая внутри коробки. Заполнение квадрата с изображением. Работа с [canvas] [img] fillStyle и drawImage () - PullRequest
0 голосов
/ 18 октября 2019

Это заняло у меня некоторое время, но я наконец-то понял, как заставить изображение выглядеть так, чтобы оно подпрыгивало внутри коробки. Решение включает в себя drawImage (). Первоначально я думал, что черный цвет коробки по умолчанию препятствует выбору моего изображения. Лучше использовать метод drawImage (), который может принимать до 5 аргументов и всего 3.

<body>
    <canvas width="400" height="400" style="background: orange"> 
        </canvas>
    <img id="bob" src="./bpTransB.png" alt="bobPig" 
          style="visibility: hidden">

<script>
  const cx = document.querySelector("canvas").getContext("2d");
  var img = document.getElementById("bob");

  var lastTime = null;
  function frame(time) {
    if (lastTime != null)
      updateAnimation(Math.min(100, time - lastTime) / 1000);
    lastTime = time;
    requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);

  var x = 100, y = 60, width = 20, height = 20, speedX = 100, speedY = 60;

  function updateAnimation(step) {
    // draws the blue box (comment cx.clearRect() back in to clear contrail)
    // cx.clearRect(0, 0, 400, 400);
    cx.strokeStyle = "blue";
    cx.lineWidth = 4;
    cx.strokeRect(0, 0, 400, 400);
    // handles the change of direction in the animation
    x += step * speedX;
    y += step * speedY;
    if (x < width - 35 || x > 373 - width)
      speedX = -speedX;
    if (y < height - 25 || y > 373 - height)
      speedY = -speedY;
    // draws the image on the canvas 
    cx.drawImage(img, x, y, 65, 55);
    cx.beginPath();   
    cx.fill();
  }
</script>
</body>
...