Итак, я пытаюсь создать метод, в котором вы перемещаете изображение вокруг элемента canvas. Это важно в том смысле, что при создании многих видов игр вам понадобится фоновое изображение, чтобы правильно перемещаться по холсту и движению игрока. Проблема в том, что вы всегда рисуете относительно точки холста (0,0) в верхнем левом углу. Итак, что я собираюсь сделать в концептуализации, где нажатие вправо (например) будет восприниматься как перемещение CANVAS вправо, когда вы действительно перемещаете изображение влево. Можно утверждать, что в этом нет необходимости, но если честно подумать об этом, то у меня болит голова. Я думаю, что этот способ связать все с большим абсолютным полем было бы проще для программирования с большим количеством объектов.
Проблема в том, что я перебираю свой код в Pycharm, но у меня постоянно возникают холсты, не определенные и похожие ошибки. Пожалуйста, помогите мне исправить это! Так что без лишних слов, вот мой код! (и любые другие способы очистки моего кода приветствуются, я довольно новичок в JS!)
//Animates a moving black dot on the canvas.
//Variables for parameters
var gameloopId;
var speed=6;
var canvas;
var background;
var circle;
var ctx;
//Wait for document to be ready then start
$(document).ready(function(){
console.log('document is ready');
init();
});
//Holds the relative coordinates.
function Canvas(){
this.x=0;//relative X
this.y=0;//relative Y
//Calulate screen height and width
this.width = parseInt($("#canvas").attr("width"));
this.height = parseInt($("#canvas").attr("height"));
}
canvas=new Canvas();
//Define an object
function Object(){
this.absX=0;
this.absY=0;
this.x=this.absX-canvas.x;
this.y=this.absY-canvas.y;
}
//Circle Object
function Circle(radius){
this.radius=radius;
}
Circle.prototype= new Object(); //Circle is an Object
function drawCircle(){
// Create the circle
ctx.strokeStyle = "#000000";
ctx.fillStyle = "#000000";
ctx.beginPath();
ctx.arc(circle.x,circle.y,circle.radius,0,Math.PI*2,true);
ctx.closePath();
ctx.stroke();
ctx.fill();
}
Background= Image();
Background.prototype=new Object(); //Background is an Object
background= new Background()
function drawBackground(){
//draw the background
ctx.drawImage(background,background.x,background.y);
}
function init(){
console.log('function init()');
initSettings();
//Insert event handler for keyboard movement of circle (space clearInterval)
$(document).keydown(function(e){
if(e.keyCode=='37'){ //Left key
circle.absX+=speed;
canvas.x+=speed;}
if(e.keyCode=='38'){ //Up key
circle.absY-=speed;
canvas.y-=speed;}
if(e.keyCode=='39'){ //Right key
circle.absX+=speed;
canvas.x+=speed;}
if(e.keyCode=='40'){ //Down key
circle.absX+=speed;
canvas.y+=speed;}
if(e.keyCode=='32'){ //Space Bar
console.log('spacebar');
clearInterval(gameloopId);
initSettings();
gameloopId = setInterval(gameLoop,10);
}
});
$(document).keyup(function(e){
if(e.keyCode=='37'){
console.log('left');}//Left key
if(e.keyCode=='38'){
console.log('up');}//Up key
if(e.keyCode=='39'){
console.log('right');}//Right key
if(e.keyCode=='40'){
console.log('down');}//Down key
});
//Initialize loop of "game"
gameloopId = setInterval(gameLoop,10);
}
function initSettings(){
console.log('initSettings');
//Set up canvas
ctx = document.getElementById('canvas').getContext('2d');
//center circle on the horizontal axis
console.log('setting circle coords');
circle = new Circle(15);
circle.x = parseInt(canvas.width/2);
circle.y = canvas.height - 40;
//Put background at (0,0)
background.x=0;
background.y=0;
background.src="http://127.0.0.1:8000/static/back.jpg";
console.log("background width:"+background.width);
console.log("background height:"+background.height);
}
function gameLoop(){
//console.log('function gameLoop()');
//Has it reached far left side?
if(circle.x<circle.radius)
{
circle.x=circle.radius
}
//Has it reached far right side?
if(circle.x>canvas.width - circle.radius)
{
circle.x=canvas.width - circle.radius
}
//Has it reached top?
if(circle.y<circle.radius)
{
circle.y=circle.radius
}
//has it reached bottom?
if(circle.y>canvas.height - circle.radius)
{
circle.y=canvas.height - circle.radius
}
//has background reached left?
if(background.x < canvas.width-background.width)
{
background.x= canvas.width-background.width;
}
//has background reached right?
if(background.x>0)
{
background.x=0;
}
//has background reached top?
if(background.y < canvas.height-background.height)
{
background.y = canvas.height-background.height;
}
//has background reached bottom?
if(background.y>0)
{
background.y=0;
}
//Clear the screen (i.e. a draw a clear rectangle the size of the screen)
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
//draw background
drawBackground();
// draw the circle
drawCircle();
ctx.restore();
}
РЕДАКТИРОВАТЬ: (ОБНОВЛЕННЫЙ КОД!)
//Animates a moving black dot on the canvas.
//Variables for parameters
var gameloopId;
var speed=6;
var canvas;
var background;
var circle;
var ctx;
//Wait for document to be ready then start
$(document).ready(function(){
console.log('document is ready');
init();
});
//Holds the relative coordinates.
function Canvas(){
this.x=0;//relative X
this.y=0;//relative Y
//Calulate screen height and width
this.width = parseInt($("#canvas").attr("width"));
this.height = parseInt($("#canvas").attr("height"));
}
//Define an object
function MyObject(){
this.absX=0;
this.absY=0;
this.x=this.absX-canvas.x;
this.y=this.absY-canvas.y;
}
//Circle MyObject
function Circle(radius){
this.radius=radius;
}
Circle.prototype= new MyObject(); //Circle is an MyObject
function drawCircle(){
// Create the circle
ctx.strokeStyle = "#000000";
ctx.fillStyle = "#000000";
ctx.beginPath();
ctx.arc(circle.x,circle.y,circle.radius,0,Math.PI*2,true);
ctx.closePath();
ctx.stroke();
ctx.fill();
}
function Background(){
this.img= Image();
}
Background.prototype=new MyObject(); //Background is an MyObject
function drawBackground(){
//draw the background
ctx.drawImage(background,background.x,background.y);
}
function init(){
console.log('function init()');
initSettings();
//Insert event handler for keyboard movement of circle (space clearInterval)
$(document).keydown(function(e){
if(e.keyCode=='37'){ //Left key
circle.absX+=speed;
canvas.x+=speed;}
if(e.keyCode=='38'){ //Up key
circle.absY-=speed;
canvas.y-=speed;}
if(e.keyCode=='39'){ //Right key
circle.absX+=speed;
canvas.x+=speed;}
if(e.keyCode=='40'){ //Down key
circle.absX+=speed;
canvas.y+=speed;}
if(e.keyCode=='32'){ //Space Bar
console.log('spacebar');
clearInterval(gameloopId);
initSettings();
gameloopId = setInterval(gameLoop,10);
}
});
$(document).keyup(function(e){
if(e.keyCode=='37'){
console.log('left');}//Left key
if(e.keyCode=='38'){
console.log('up');}//Up key
if(e.keyCode=='39'){
console.log('right');}//Right key
if(e.keyCode=='40'){
console.log('down');}//Down key
});
//Initialize loop of "game"
gameloopId = setInterval(gameLoop,10);
}
function initSettings(){
console.log('initSettings');
//Set up canvas
canvas=new Canvas();
ctx = document.getElementById('canvas').getContext('2d');
//center circle on the horizontal axis
console.log('setting circle coords');
circle = new Circle(15);
circle.x = parseInt(canvas.width/2);
circle.y = canvas.height - 40;
//Put background at (0,0)
background= new Background();
background.x=0;
background.y=0;
background.img.src="http://127.0.0.1:8000/static/back.jpg";
console.log("background width:"+background.width);
console.log("background height:"+background.height);
}
function gameLoop(){
//console.log('function gameLoop()');
//Has it reached far left side?
if(circle.x<circle.radius)
{
circle.x=circle.radius
}
//Has it reached far right side?
if(circle.x>canvas.width - circle.radius)
{
circle.x=canvas.width - circle.radius
}
//Has it reached top?
if(circle.y<circle.radius)
{
circle.y=circle.radius
}
//has it reached bottom?
if(circle.y>canvas.height - circle.radius)
{
circle.y=canvas.height - circle.radius
}
//has background reached left?
if(background.x < canvas.width-background.width)
{
background.x= canvas.width-background.width;
}
//has background reached right?
if(background.x>0)
{
background.x=0;
}
//has background reached top?
if(background.y < canvas.height-background.height)
{
background.y = canvas.height-background.height;
}
//has background reached bottom?
if(background.y>0)
{
background.y=0;
}
//Clear the screen (i.e. a draw a clear rectangle the size of the screen)
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
//draw background
drawBackground();
// draw the circle
drawCircle();
ctx.restore();
}
enter code here