我正在尝试制作一个跟随玩家的屏幕,以便玩家位于屏幕的中间。我已经在另一个游戏中做到了,但在这里不起作用。这是我的代码:
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在“屏幕” Canvas 中绘制蓝色和红色 Canvas
最佳答案
好的,从你的评论中我明白了你在寻找什么。但问题是你可能在没有理解的情况下就从一个例子开始。我尝试向您提供我对所做工作的解释,但您应该寻找一个从基础知识开始并深化动画的良好指南(例如: 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();
}
编辑正确答案
错误在于对象“player”的位置。它位于 Canvas 外部,宽度:500 高度:500,“玩家”位于 x:700 y:800 位置。
更改您的副本将出现的玩家的位置。
var player = {
x : 50,
y : 50
}
关于javascript - DrawImage() 不在 Canvas 上绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34598099/