DrawImage() 不在 canvas 上绘制

DrawImage() doesn't draw on canvas

我正在尝试制作一个跟随玩家的屏幕,以便玩家位于屏幕中间。我已经在另一个游戏中做到了,但是在这里它不起作用。这是我的代码:

var c = document.getElementById("main");
var ctx = c.getContext("2d");
var screen = document.getElementById("screen").getContext("2d");
var WhatUSeeWidth = document.getElementById("screen").width;
var WhatUSeeHeight = document.getElementById("screen").height;

ctx.beginPath();
for (i = 0; i < 100; i ++) {
    if (i % 2) {
      ctx.fillStyle = "red";
    }
    else {
      ctx.fillStyle = "blue";
    }
    ctx.fillRect(0, i * 100, 500, 100);
} 

var player = {
 x : 700,
 y : 800
}

setInterval(tick, 100);

function tick() {
  screen.beginPath();
  screen.drawImage(c, player.x - WhatUSeeWidth / 2, player.y - WhatUSeeHeight / 2, WhatUSeeWidth, WhatUSeeHeight, 0, 0, WhatUSeeWidth, WhatUSeeHeight);
}
canvas {
     border: 2px solid black;
   }
<canvas id="main" width="500" height="500"h></canvas>
 <canvas id="screen" width="500" height="500"></canvas>

我想在 "screen" canvas 中绘制蓝色和红色 canvas 使用 drawImage

好的,从你的评论中我明白了你在找什么。但问题是你可能在没有理解的情况下从一个例子开始。我试着给你我对你所做的事情的解释,但你应该寻找一个从基础开始并深化动画的好指南(例如:http://www.html5canvastutorials.com/)。

HTML

<canvas id="canvasLayer" width="500" height="500"></canvas>

Javascript

var canvas = document.getElementById("canvasLayer");
var context = canvas.getContext("2d");
var WhatUSeeWidth = document.getElementById("canvasLayer").width;
var WhatUSeeHeight = document.getElementById("canvasLayer").height;

var player = {
    x : 0,
    y : 0
}

function drawBackground() {
  for (i = 0; i < 100; i ++) {
      if (i % 2) {
        context.fillStyle = "red";
      }
      else {
        context.fillStyle = "blue";
      }
      context.fillRect(0, i * 100, 500, 100);
  } 
}

function playerMove() {
  context.beginPath();
  var radius = 5;
  context.arc(player.x, player.y, radius, 0, 2 * Math.PI, false);
  context.fillStyle = 'green';
  context.fill();
  context.lineWidth = 1;
  context.strokeStyle = '#003300';
  context.stroke();
}

setInterval(tick, 100);

function tick() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  drawBackground();

  player.x++;
  player.y++;
  playerMove();
}

This is the JSFiddle.

编辑正确答案

错误在对象的位置"player"。它位于 canvas、width:500 height:500 之外,而 "player" 位于 x:700 y:800.

的位置

正在更改您的副本将出现的播放器的位置。

var player = {
    x : 50,
    y : 50
}

Here the jsfiddle example.