DrawImage()不在画布上绘制

时间:2016-01-04 19:08:39

标签: javascript canvas drawimage

我正在尝试按照播放器制作一个屏幕,以便播放器位于屏幕中间。我已经在另一个游戏中制作了它,但在这里它不起作用。这是我的代码:

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>

我想在“屏幕”画布中使用drawImage

绘制蓝色和红色画布

1 个答案:

答案 0 :(得分:0)

好的,从你的评论我明白你在找什么。但问题是你可能从没有理解的例子开始。我试着向你解释你做了什么,但是你应该寻找一个好的指南,从基础开始并加深动画(例如: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

使用正确的答案进行编辑

错误位于对象“播放器”的位置。它位于画布外面,宽度:500高度:500,“播放器”位于x:700 y:800。

更改播放器的位置。

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

Here the jsfiddle example.