Javascript на html Проблема элемента Canvas - PullRequest
0 голосов
/ 26 июля 2011

Итак, я пытаюсь создать метод, в котором вы перемещаете изображение вокруг элемента 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

Ответы [ 3 ]

1 голос
/ 26 июля 2011
Background= Image();
Background.prototype=new Object(); //Background is an Object
background= new Background()

кажется подозрительным.редактировать: фон является элементом.Вы добавляете прототип, даже если он не является функцией.Затем вы вызываете Background как конструктор, но это не так.

Так что фон, вероятно, будет неопределенным.Я удивлен, что background.x дает вам 0. Кстати, вам нужно parseInt(arg, 10), чтобы получить ваш результат в десятичном, а не восьмеричном.

1 голос
/ 26 июля 2011

Я не думаю, что вы можете написать свой собственный Object Вы определенно не можете использовать Object, это зарезервированное ключевое слово . Объект - это встроенный объект JavaScript, от которого наследуются все объекты. Вы в основном перезаписали это. Это может быть вашей проблемой.

Попробуйте назвать его myObject, чтобы проверить, не в этом ли проблема.

//Define an myObject
function myObject(){
    this.absX=0;
    this.absY=0;
    this.x=this.absX-canvas.x;
    this.y=this.absY-canvas.y;
}

Circle.prototype= new myObject(); //Circle is a myObject
0 голосов
/ 27 июля 2011

Я понял это!У меня было много глупостей в моей оде и много ошибок - например, background.img - это Image, но везде я пытался получить background.width вместо background.img.width.Я также переработал несколько функций, чтобы сделать их красивее (по крайней мере, для них).Спасибо выше за вашу помощь!Вот мой «окончательный» код, по крайней мере, на данный момент:

//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.
var canvas = new 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;

    this.updateplace = function (){
        this.x=this.absX-canvas.x;
        this.y=this.absY-canvas.y;
    };
}

//Circle MyObject
function Circle(radius){
    this.radius=radius;
    this.draw=function(){
        // 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();
    }
}
Circle.prototype= new MyObject(); //Circle is an MyObject

function Background(){
    this.img= Image();
    this.draw=function(){
        ctx.drawImage(background.img,background.x,background.y);
    }
}
Background.prototype=new MyObject(); //Background is an MyObject

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.absY+=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');
    canvas.width = parseInt($("#canvas").attr("width"));
    canvas.height = parseInt($("#canvas").attr("height"));

    //center circle on the horizontal axis
    console.log('setting circle coords');
    circle = new Circle(15);
    circle.absX = parseInt(canvas.width/2);
    circle.absY = 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.img.width);
    console.log("background height:"+background.img.height);
    console.log("Right Bound:"+(background.img.width- canvas.width))
}

function gameLoop(){
    //console.log('function gameLoop()');

    //Has it reached far left side?
    if(circle.absX<circle.radius)
    {
        circle.absX=circle.radius
    }

    //Has it reached far right side?

    if(circle.absX>background.img.width - circle.radius)
    {
        circle.absX=background.img.width - circle.radius
    }

    //Has it reached top?
    if(circle.absY<circle.radius)
    {
        circle.absY=circle.radius
    }

    //has it reached bottom?
    if(circle.absY>background.img.height - circle.radius)
    {
        circle.absY=background.img.height - circle.radius
    }

    //has canvas reached right bound?
    if(canvas.x > background.img.width- canvas.width)
    {
        canvas.x= background.img.width- canvas.width;
    }

    //has canvas reached left bound?
    if(canvas.x<0)
    {
        canvas.x=0;
    }

    //has background reached bottom bound?
    if(canvas.y > background.img.height - canvas.height)
    {
        canvas.y = background.img.height - canvas.height;
    }

    //has background reached top bound?
    if(canvas.y<0)
    {
        canvas.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
    background.updateplace();
    background.draw();
    // draw the circle
    circle.updateplace();
    circle.draw();


    ctx.restore();

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...