Canvas javascript метод drawImage - PullRequest
       3

Canvas javascript метод drawImage

1 голос
/ 24 апреля 2020

Результат: изображение не загружается на холст. У меня белый прямоугольник, есть идеи, почему? Я подумал, что могу просто вызвать метод draw непосредственно из переменной, например, например: bg.draw, или это означает, что мне нужно заново нарисовать изображение на холсте и повторно запустить bg.draw?

const cvs = document.getElementById("firstplatform");
const ctx = cvs.getContext("2d");

// GAME VARS AND CONSTS
let frames = 0;

// LOAD IMAGE
const sprite = new Image();
sprite.src = "img/sprite.png";

//BACKGROUND
const bg = {
  sX: 0,
  sY: 0,
  w: 275,
  h: 226,
  x: 0,
  y: cvs.height - 226,


  draw: function () {
    ctx.drawImage(
      sprite,
      this.sX,
      this.sY,
      this.w,
      this.h,
      this.x,
      this.y,
      this.w,
      this.h
    );
    ctx.drawImage(
      sprite,
      this.sX,
      this.sY,
      this.w,
      this.h,
      this.x + this.w,
      this.y,
      this.w,
      this.h
    );
  },
};

// DRAW
bg.draw();`

Ниже приведен индекс. html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>First Game</title>
    <link href="https://fonts.googleapis.com/css?family=Teko:700" rel="stylesheet">
    <style>        
        canvas{
            border: 1px solid #000;
            display: block;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <canvas id="firstplatform" width="320" height="480"></canvas>


    <script src="game.js"></script>
</body>
</html>

1 Ответ

1 голос
/ 24 апреля 2020

Вам нужно дождаться загрузки изображения, прежде чем вы сможете нарисовать его на холсте. Итак, заверните bg.draw в обработчик загрузки:

sprite.onload = function()
{
  bg.draw();
}

const cvs = document.getElementById("firstplatform");
const ctx = cvs.getContext("2d");

// GAME VARS AND CONSTS
let frames = 0;

// LOAD IMAGE
const sprite = new Image();
sprite.src = "https://cdn.sstatic.net/Img/unified/sprites.svg?v=fcc0ea44ba27";

//BACKGROUND
const bg = {
  sX: 0,
  sY: 0,
  w: 275,
  h: 226,
  x: 0,
  y: cvs.height - 226,


  draw: function () {
    ctx.drawImage(
      sprite,
      this.sX,
      this.sY,
      this.w,
      this.h,
      this.x,
      this.y,
      this.w,
      this.h
    );
    ctx.drawImage(
      sprite,
      this.sX,
      this.sY,
      this.w,
      this.h,
      this.x + this.w,
      this.y,
      this.w,
      this.h
    );
  },
};

sprite.onload = function()
{
  bg.draw();
}
<canvas id="firstplatform" width="320" height="480"></canvas>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...