ساخت بازی با کانواس و جاوا اسکریپت

saalek110

Well-Known Member
صفحه۷:
لینک کلی دوم هم تمام شد.
بازی های خوبی بینشون هست که پست زدم.
 

saalek110

Well-Known Member

بررسی پروژه چهارم سورس بالا:
از quachngocxuan.

Screenshot_۲۰۲۴-۰۲-۲۱_۱۵۲۲۲۶.jpg
همان طور که در شکل بالا می بینید یک فرم داریم ...
محتوای فایل html:
HTML:
<!DOCTYPE html>
<html>
<head>
    <title>Pixel Art Maker!</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
    <link rel="stylesheet" href="styles.css">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
    <h1>Lab: Pixel Art Maker</h1>

    <h2>Choose Grid Size</h2>
    <form id="sizePicker">
        Grid Height:
        <input type="number" id="input_height" name="height" min="1" value="1">
        Grid Width:
        <input type="number" id="input_width" name="width" min="1" value="1">
        <input type="submit" id="submit">
    </form>

    <h2>Pick A Color</h2>
    <input type="color" id="colorPicker">

    <h2>Design Canvas</h2>
    <table id="pixel_canvas"></table>

    <script src="designs.js"></script>
</body>
</html>
و محتوای فایل designs.js:

JavaScript:
// Select color input
var color = $("#colorPicker").val();
$("#colorPicker").on("change", (evt) => {
  color = $("#colorPicker").val();
});

// When size is submitted by the user, call makeGrid()
$("#submit").on("click", evt => {
    evt.preventDefault();
    
    // Main program
    let height = parseInt($("#input_height").val());
    let width = parseInt($("#input_width").val());
    let canvas = $("#pixel_canvas");
    let grid = new Grid(width, height, canvas);
    grid.makeGrid();
});

var Grid = function(width, height, canvas) {
    this.width = width;
    this.height = height;
    this.canvas = canvas;
}

Grid.prototype.makeGrid = function() {
    var table = new Table(this.height, this.width);
    table.generate();
    table.attachClick();
    this.canvas.html(table.tableEle);
};

var Table = function(nRows, nCols) {
    this.nRows = nRows;
    this.nCols = nCols;
    this.tableEle = undefined;
    
    this.tableTag = "<table></table>";
    this.rowTag = "<tr></tr>";
    this.cellTag = "<td></td>";
}

Table.prototype.generate = function() {
    this.tableEle = $(this.tableTag);
    for (row = 0; row < this.nRows; row++) {
        var rowEle = $(this.rowTag);
        for (column = 0; column < this.nCols; column++) {
            var columnEle = $(this.cellTag);
            rowEle.append(columnEle);
        }
    
        this.tableEle.append(rowEle);
    }
};

Table.prototype.attachClick = function() {
    $(this.tableEle).find("td").on("click", function(evt) {
        $(this).css("background-color", color);
    });
};
 

saalek110

Well-Known Member
با نگاه به کدهای بالا:
اطلاعاتی از فرم گرفته و یک table از html ساخته.

ولی یک table معمولی نیست. چون با تاچ رنگی میشه هر سلول.
برنامه را اینجا آپلود کردم:


با کدهای جاوا اسکریپت table ساخته و به اون تابعی نسبت داده که با لمس رنگ بکگراند background-color عوض بشه.
البته من کدهای پوشه ۷ را در پست قبل زدم. .پوشه ۱ که اسمش نرمال ورژن است اینه کدش:
JavaScript:
// Select color input
var color = $("#colorPicker").val();
$("#colorPicker").on("change", function(evt) {
  color = $("#colorPicker").val();
});

// When size is submitted by the user, call makeGrid()
$("#submit").on("click", function(evt) {
    evt.preventDefault();
 
    makeGrid();
});

// Function to making the game's grid
function makeGrid() {
  // Your code goes here!
 
  // Select size input
  var height = parseInt($("#input_height").val());
  var width = parseInt($("#input_width").val());

  // Get table setup information
  var canvas = $("#pixel_canvas");
 
  // Generate table cells and add listeners
  var tableEle = $("<table></table>");
  for (row = 0; row < height; row++) {
    var rowEle = $("<tr></tr>");
    for (column = 0; column < width; column++) {
        var columnEle = $("<td></td>");
        rowEle.append(columnEle);
    }
 
    tableEle.append(rowEle);
  }
 
  // Attach event for cells
  $(tableEle).find("td").on("click", function(evt) {
    $(this).css("background-color", color);
  });

  canvas.html(tableEle);
}
 
آخرین ویرایش:

saalek110

Well-Known Member


JavaScript:
let canvas = document.getElementById('hello-world-canvas')
let context = canvas.getContext('2d')


// Blue reactangle
context.fillStyle = "blue";
context.fillRect(10, 40, 30, 70);

// Yellow reactangle
context.fillStyle = "yellow"
context.fillRect(50, 30, 60, 60); //Dikdörtgen

اولین پوشه اش حاوی این کد بود.... رسم مربع است.

دومین پوشه رسم خط:
JavaScript:
window.onload = () => {
    let canvas = document.getElementById('hello-world-canvas')
    let context = canvas.getContext('2d')

    //Draw line steps
    context.beginPath(); //reset the context state
    context.strokeStyle = "red"; //line color
    context.lineWidth = 10; //line width
    context.moveTo(30, 70); //moveTo(x,y)->starting point of line
    context.lineTo(130, 70); //line(x,y) end point of the line
    context.stroke() //drawe line
}

از window استفاده کرده.رویداد load پنجره.
این هم خطهای دنبال هم. دیگه باقی کدهای اول و آخرش را نذاشتم. مثل کد قبلی فرض کنید:
JavaScript:
   context.beginPath(); //reset the context state
    context.moveTo(30, 30); //moveTo(x,y)->starting point of line
    context.lineTo(80, 80); //line(x,y) end point of the line
    context.lineTo(130, 30); //line(x,y) end point of the line
    context.lineTo(180, 80); //line(x,y) end point of the line
    context.lineTo(230, 30); //line(x,y) end point of the line

    context.stroke() //drawe line
 
آخرین ویرایش:

saalek110

Well-Known Member
JavaScript:
window.onload = () => {
    let canvas = document.querySelector('canvas')
    let context = canvas.getContext('2d')


    let image = new Image();
    image.src = "assets/img/amsterdam.jpg"
    image.onload = () => {
        context.drawImage(image, 180, 35)


        let imageData = context.getImageData(180, 35, 550, 366)
        console.log(imageData)
        for (let i = 0; i < imageData.data.length; i += 4) {

            let average = (imageData.data[i] + imageData.data[i + 1] + imageData.data[i + 2]) / 3;

            imageData.data[i] = average; // Red
            imageData.data[i + 1] = average; // Green
            imageData.data[i + 2] = average; //Blue

        }
        context.putImageData(imageData, 180, 35)

        //Save canvas image as data url (default:png)
        let dataUrl = canvas.toDataURL();

        let canvasImg = document.getElementById('canvasImg');


        const link = document.createElement('a')
        link.href = dataUrl;
        link.setAttribute('download', 'handsome')
        link.innerHTML = `<img src="${dataUrl}" alt="Right click to save image"/>`
        canvasImg.appendChild(link)
    }

}
فایل html اون چیزی نداره:
HTML:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>

<body>

    <canvas width="900" height="700">
        This is fallback message for old browser.
    </canvas>



    <div id="canvasImg"></div>


</body>

</html>
<script src="assets/js/script.js"></script>

اجرای برنامه عکس زیر:

Screenshot_۲۰۲۴-۰۲-۲۱_۱۷۱۶۴۱.jpg

که با زدن روی عکس پایینی ، عکس دانلود میشه.
سالک: بعدا ممکن است وارد این بحث شویم.
 
آخرین ویرایش:

saalek110

Well-Known Member
JavaScript:
window.onload = () => {
    let canvas = document.querySelector('canvas')
    let context = canvas.getContext('2d')



    context.fillStyle = "red";
    context.fillRect(240, 100, 120, 120);
    context.save();



    context.fillStyle = "green";
    context.fillRect(380, 100, 120, 120);
    context.save();



    context.fillStyle = "blue";
    context.fillRect(540, 100, 120, 120);
    context.save();

    context.restore()
    context.fillRect(240, 300, 120, 120);

    context.restore()
    context.fillRect(380, 300, 120, 120);

    context.restore()
    context.fillRect(540, 300, 120, 120);
}

Screenshot_۲۰۲۴-۰۲-۲۱_۱۷۲۹۱۴.jpg
اجرای بالا نشان می دهد که save ها مثل پشته روی هم انباشته می شوند. یعنی آخرین save میشه اولین بازیافت..و اولین save میشه آخرین بازیافت.... به اعداد مختصات نکاه کنید... ۳ مربع آخری دارای y برابر ۳۰۰ هستند ، یعنی ۳ مربع آخری ، در عکس اون ۳ مربع پایینی هستند. و اگر به x اونها نگاه کنید می بینید افزایش یابنده است ، یعنی از چپ به راست چیده می شوند. چون نقطه صفر و صفر بالا و چپ است.
 

saalek110

Well-Known Member
JavaScript:
window.onload = () => {
    let canvas = document.querySelector('canvas')
    let context = canvas.getContext('2d')


    let patternImage = new Image();
    patternImage.src = "assets/img/apple.png";

    patternImage.onload = () => {
        let pattern = context.createPattern(patternImage, 'repeat');
        context.fillStyle = pattern;
        context.fillRect(0, 0, 900, 400);
    }


}

Screenshot_۲۰۲۴-۰۲-۲۱_۱۷۳۵۲۱.jpg

این کدها از همون صفحه ای است که در بالا معرفی کردم.فایل html اون چیزی نداره...:
HTML:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>

<body>

    <canvas width="900" height="400">
        This is fallback message for old browser.
    </canvas>


</body>

</html>
<script src="assets/js/script.js"></script>

پس اگر خواستید به جای رنگ کردن ، کاغذ دیواری کنید ، راهش اینه.
یک پترن داریم ، یک پترن ایمیج. با پترن fill می کنیم.
 

saalek110

Well-Known Member
JavaScript:
window.onload = () => {
    let canvas = document.querySelector('canvas')
    let context = canvas.getContext('2d')


    let gradient = context.createRadialGradient(570, 380, 300, 570, 300, 20);
    gradient.addColorStop(0, "red")
    gradient.addColorStop(0.25, "brown")
    gradient.addColorStop(0.5, "yellow")
    gradient.addColorStop(0.75, "green")
    gradient.addColorStop(1, "blue")

    context.strokeStyle = "blue";
    context.lineWidth = 4;
    context.fillStyle = gradient;
    context.rect(240, 40, 420, 420);
    context.stroke();
    context.fill();
}

Screenshot_۲۰۲۴-۰۲-۲۱_۱۷۴۱۴۷.jpg
گرادیانت.
 

saalek110

Well-Known Member
JavaScript:
window.onload = () => {
    let canvas = document.querySelector('canvas')
    let context = canvas.getContext('2d')


    var start = new Date();
    window.requestAnimationFrame(drawRandomColoredRectangle);

    function drawRandomColoredRectangle() {

        var now = new Date();
        if (now - start >= 500) {
            start = now;


            //Clear Canvas
            context.clearRect(0, 0, canvas.width, canvas.height)

            let color = createRandomRGBColor();
            let fillOpacity = Math.random();
            let fillColor = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + fillOpacity + ')';
            let borderColor = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ')';

            let x = getRandomInt(0, canvas.width);
            let y = getRandomInt(0, canvas.height);
            let w = getRandomInt(0, canvas.width - x);
            let h = getRandomInt(0, canvas.height - y);

            // Draw Reactangle
            context.beginPath()
            context.fillStyle = fillColor;
            context.strokeStyle = borderColor;
            context.rect(x, y, w, h);
            context.stroke();
            context.fill();
        }

        //Animate
        window.requestAnimationFrame(drawRandomColoredRectangle);

    }


    function createRandomRGBColor() {
        var red = getRandomInt(0, 257);
        var green = getRandomInt(0, 257);
        var blue = getRandomInt(0, 257);
        return { r: red, g: green, b: blue };
    };

    function getRandomInt(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min)) + min;
    }

    window.requestAnimationFrame = (function() {
        return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(callback) {
                window.setTimeout(callback, 1000 / 60);
            };
    })();

}
انیمیشن.
در اجرا یک سری مستطیل ها با رنگ های مختلف ، تند و تند ظاهر و ناپدید می شوند. حالت چشمک زدن.
 

saalek110

Well-Known Member
JavaScript:
window.onload = () => {
    let canvas = document.querySelector('canvas')
    let context = canvas.getContext('2d')

    let ballX = 400;
    let ballY = 300;
    let ballRadius = 30;
    let ballColor = "orange";
    let changeX = 4;
    let changeY = 4;

    window.requestAnimationFrame(animationLoop);

    function animationLoop() {

        //Clear Canvas
        context.clearRect(0, 0, canvas.width, canvas.height);

        //Update
        if (ballY + ballRadius > canvas.height) {
            changeY *= -1;
        }
        if (ballX + ballRadius > canvas.width) {
            changeX *= -1;
        }
        if (ballY - ballRadius < 0) {
            changeY *= -1;
        }
        if (ballX - ballRadius < 0) {
            changeX *= -1;
        }
        ballX += changeX;
        ballY += changeY;
        //Draw
        drawBall(ballX, ballY, ballRadius, ballColor)

        //Animate
        window.requestAnimationFrame(animationLoop);
    }
    function drawBall(x, y, radius, color) {
        var radian = Math.PI / 100;

        context.beginPath();
        context.strokeStyle = color;
        context.fillStyle = color;
        context.arc(x, y, radius, 0, 360 * radian, false)
        context.stroke();
        context.fill();
    }
    window.requestAnimationFrame = (function() {
        return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(callback) {
                window.setTimeout(callback, 1000 / 60);
            };
    })();
}

نتیجه اجرا توپی که به دیوارها می خورد و بر می گردد.
 

پیوست ها

  • Screenshot_۲۰۲۴-۰۲-۲۱_۱۷۵۰۴۰.jpg
    Screenshot_۲۰۲۴-۰۲-۲۱_۱۷۵۰۴۰.jpg
    18.9 کیلوبایت · بازدیدها: 0

saalek110

Well-Known Member
JavaScript:
window.onload = () => {
    let canvas = document.querySelector('canvas')
    let context = canvas.getContext('2d')

    let cellWidth = 192;
    let cellHeight = 200;

    let tile = new Image()
    tile.src = "assets/img/tile.png";
    tile.onload = () => {
        context.drawImage(tile, 0, 0, 768, 200, 60, 0, 768, 200);
        drawTileCell(3)
    }
    window.requestAnimationFrame(animationLoop)

    let cell = 0;
    let start = new Date();

    function animationLoop() {

        let now = new Date();
        if (now - start >= 100) {
            start = now;
            //Clear
            context.clearRect(0, 200, canvas.width, canvas.height - 200);
            //Update
            cell++;
            cell %= 4;
            drawTileCell(cell);
        }
        //Animate
        window.requestAnimationFrame(animationLoop)
    }

    function drawTileCell(index) {
        context.drawImage(tile, index * cellWidth, 0, cellWidth, cellHeight, 360, 200, cellWidth, cellHeight);
    }

    window.requestAnimationFrame = (function() {
        return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(callback) {
                window.setTimeout(callback, 1000 / 60);
            };
    })();
}

نتیجه اجرا در عکس زیر:
عکس پایینی متحرک است.

Screenshot_۲۰۲۴-۰۲-۲۱_۱۷۵۸۲۴.jpg

یک عکس در پوشه عکسش هست که ضمیمه می کنم:
با نام tile.png:

tile.png
 

saalek110

Well-Known Member
JavaScript:
window.onload = () => {
    let canvas = document.querySelector('canvas')
    let context = canvas.getContext('2d')

    let isBackgroundLoaded = false;
    let isHeroLoaded = false;

    //Cell Specifications
    let cellWidth = 256,
        cellHeight = 256,
        currentCell = 0;

    // Time Specifications
    let animationStart = new Date();

    //// Move Specifications
    let moveAmount = 15;
    let moveX = 100;


    let background = new Image();
    background.src = "assets/img/back.png";
    background.onload = () => {
        isBackgroundLoaded = true;
    }

    let hero = new Image();
    hero.src = "assets/img/sprite.png";
    hero.onload = () => {
        isHeroLoaded = true;
    }

    window.requestAnimationFrame(animationLoop)

    function animationLoop() {

        let animationNow = new Date();
        if (animationNow - animationStart >= 100) {
            animationStart = animationNow;

            //Clear
            context.clearRect(0, 0, canvas.width, canvas.height);

            //Update
            currentCell++;
            currentCell %= 6;
            if (moveX >= canvas.width) {
                moveX = -1 * cellWidth;
            } else {
                moveX += moveAmount;

            }

            //Draw
            if (isBackgroundLoaded) {
                context.drawImage(background, 0, 0, canvas.width, canvas.height);
            }
            if (isHeroLoaded) {
                context.drawImage(hero, currentCell * cellWidth, 0, cellWidth, cellHeight, moveX, 320, 100, 100);
            }
        }


        //Animate
        window.requestAnimationFrame(animationLoop)
    }

    window.requestAnimationFrame = (function() {
        return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(callback) {
                window.setTimeout(callback, 1000 / 60);
            };
    })();
}

پسری که راه می رود:

Screenshot_۲۰۲۴-۰۲-۲۱_۱۸۰۷۴۵.jpg
 

saalek110

Well-Known Member
JavaScript:
window.onload = () => {
    let canvas = document.querySelector('canvas')
    let context = canvas.getContext('2d')


    //Red RectAngle
    context.fillStyle = "red"
    context.fillRect(250, 250, 400, 160);
    context.fill();

    //Scale
    context.scale(0.5, 0.5);

    //Blue RectAngle
    context.fillStyle = "blue"
    context.fillRect(250, 250, 400, 160);
    context.fill();


    context.scale(0.5, 0.5);

    //Green RectAngle
    context.fillStyle = "green"
    context.fillRect(250, 250, 400, 160);
    context.fill();


    context.scale(0.5, 0.5);

    //Green RectAngle
    context.fillStyle = "black"
    context.fillRect(250, 250, 400, 160);
    context.fill();
}

Screenshot_۲۰۲۴-۰۲-۲۱_۱۸۱۲۱۸.jpg
 

saalek110

Well-Known Member
JavaScript:
window.onload = () => {
    let canvas = document.querySelector('canvas')
    let context = canvas.getContext('2d')


    let radian = Math.PI / 180;
    context.rotate(50 * radian);

    context.fillStyle = "red";
    context.fillRect(250, 250, 400, 160);
    context.fill();


}
 

saalek110

Well-Known Member
JavaScript:
window.onload = () => {
    let canvas = document.querySelector('canvas')
    let context = canvas.getContext('2d')


    //Original
    context.fillStyle = "red";
    context.fillRect(50, 50, 160, 160);
    context.fill();

    context.translate(300, 200);


    //Translated
    context.fillStyle = "red";
    context.fillRect(0, 0, 160, 160);
    context.fill();

}

Screenshot_۲۰۲۴-۰۲-۲۱_۱۸۱۷۴۷.jpg
 

saalek110

Well-Known Member
JavaScript:
window.onload = () => {
    let canvas = document.querySelector('canvas')
    let context = canvas.getContext('2d')




    // Red RectAngle
    context.fillStyle = "red";
    context.fillRect(150, 150, 200, 100);
    context.fill();

    //Scale Transform
    context.resetTransform()


    // Blue RectAngle
    context.fillStyle = "blue";
    context.fillRect(150, 150, 200, 100);
    context.fill();

    //Scale Transform
    context.transform(1.5, 0, 0, 1.5, 0, 0)


    // Green RectAngle
    context.fillStyle = "green";
    context.fillRect(150, 150, 200, 100);
    context.fill();

    //Scale Transform
    context.resetTransform()

    // Purple RectAngle

    context.fillStyle = "purple";
    context.fillRect(150, 150, 200, 100);
    context.fill();

}

Screenshot_۲۰۲۴-۰۲-۲۱_۱۸۱۹۲۲.jpg
 

saalek110

Well-Known Member
JavaScript:
function Ball(radius, color) {
    // Base
    var ball = this;

    // Specifications
    ball.r = radius || 10; // ball radius
    ball.c = color || 'red'; // ball color
    ball.x = 0; // center x
    ball.y = 0; // center y
    ball.m = 0; // mass
    ball.vx = 0; // velocity of x direction of ball
    ball.vy = 0; // velocity of y direction of ball
    ball.context = null // the drawing context of ball
}

Ball.prototype.draw = function() {
    // Base
    var ball = this;

    // Check Context
    if (!ball.context) { return }

    // Draw Ball
    ball.context.beginPath();
    ball.context.fillStyle = ball.c;
    ball.context.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI);
    ball.context.fill();
};

JavaScript:
window.onload = function() {

    // Definitions
    var canvas = document.querySelector("canvas");
    var context = canvas.getContext("2d");


    var ball = new Ball(30, 'purple');
    ball.x = 400;
    ball.y = 320;
    ball.context = context;
    ball.draw();



    //window.requestAnimationFrame(animationLoop);

    function animationLoop() {

        // Clear Canvas
        context.clearRect(0, 0, canvas.width, canvas.height);

        // Update

        // Draw

        // Animate
        window.requestAnimationFrame(animationLoop);
    }


    window.requestAnimationFrame = (function() {
        return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(callback) {
                window.setTimeout(callback, 1000 / 60);
            };
    })();
};

Screenshot_۲۰۲۴-۰۲-۲۱_۱۸۲۳۳۸.jpg

سالک: بحث فیزیک می خواد شروع بشه ، فکر کنم با کد ساده بالا می خواهد اول ساختار را نشون بده.
 

saalek110

Well-Known Member
JavaScript:
window.onload = function() {

    // Definitions
    var canvas = document.querySelector("canvas");
    var context = canvas.getContext("2d");

    // What is velocity?
    // Velocity is the rate of change in an object's position.
    // Velocity has a magnitude (speed) and a direction.
    // Velocity is a vector quantity.
    // Velocity is represented by the formula:
    // Velocity = Δx/Δt



    var ball = new Ball(30, 'purple');
    ball.x = 100;
    ball.y = 150;
    ball.context = context;
    ball.draw();



    window.requestAnimationFrame(animationLoop);


    // Velocity
    ball.vx = 1;
    ball.vy = 1;

    function animationLoop() {

        // Clear Canvas
        context.clearRect(0, 0, canvas.width, canvas.height);

        // Update
        ball.x = ball.x + ball.vx;
        ball.y = ball.y + ball.vy;
        // Draw
        ball.draw()

        // Animate
        window.requestAnimationFrame(animationLoop);
    }


    window.requestAnimationFrame = (function() {
        return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(callback) {
                window.setTimeout(callback, 1000 / 60);
            };
    })();
};

حالا همان توپ که در پست قبل دیدید ، به شکل مورب می ره پایین و از صفحه خارج میشه.
 

saalek110

Well-Known Member
JavaScript:
window.onload = function() {

    // Definitions
    var canvas = document.querySelector("canvas");
    var context = canvas.getContext("2d");

    // What is acceleration?
    // Acceleration is the rate of change of velocity of an object with respect to time
    // Acceleration is a vector quantity.
    // Acceleration is represented by the formula:
    // Acceleration = Δv/Δt




    var ball = new Ball(30, 'purple');
    ball.x = 100;
    ball.y = 150;
    ball.context = context;
    ball.draw();



    window.requestAnimationFrame(animationLoop);


    // Velocity
    ball.vx = 1;
    ball.vy = 0.05;


    //Acceleration
    var ax = 1;
    var ay = 0.5;

    function animationLoop() {

        // Clear Canvas
        context.clearRect(0, 0, canvas.width, canvas.height);

        // Update

        // X
        //  ball.vx = ball.vx + ax; //ivme
        //   ball.x = ball.x + ball.vx; //hız artma


        // Y
        ball.vy = ball.vy + ay; //ivme
        ball.y = ball.y + ball.vy;



        // Draw
        ball.draw()

        // Animate
        window.requestAnimationFrame(animationLoop);
    }


    window.requestAnimationFrame = (function() {
        return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(callback) {
                window.setTimeout(callback, 1000 / 60);
            };
    })();
};

حالا توپ به حالت سقوط می افتد.
 

saalek110

Well-Known Member
JavaScript:
window.onload = function() {

    // Definitions
    var canvas = document.querySelector("canvas");
    var context = canvas.getContext("2d");



    var g = 0.098; //gravity

    //Ball 1
    var ball1 = new Ball(20, 'purple');
    ball1.x = 200;
    ball1.y = 80;
    ball1.context = context;
    ball1.draw();



    //Ball 2
    var ball2 = new Ball(20, 'red');
    ball2.x = 300;
    ball2.y = 80;
    ball2.context = context;
    ball2.draw();


    //Ball 3
    var ball3 = new Ball(20, 'red');
    ball3.x = 500;
    ball3.y = 500;
    ball3.context = context;
    ball3.draw();

    window.requestAnimationFrame(animationLoop);


    //Velocity
    ball1.vy = 0;
    ball2.vy = 5;
    ball3.vy = -10;



    function animationLoop() {

        // Clear Canvas
        context.clearRect(0, 0, canvas.width, canvas.height);

        // Update

        //Ball 1
        ball1.vy = ball1.vy + g;
        ball1.y = ball1.y + ball1.vy;

        //Ball 2
        ball2.vy = ball2.vy + g;
        ball2.y = ball2.y + ball2.vy;

        //Ball 3
        ball3.vy = ball3.vy + g;
        ball3.y = ball3.y + ball3.vy;

        // Draw
        ball1.draw()
        ball2.draw()
        ball3.draw()

        // Animate
        window.requestAnimationFrame(animationLoop);
    }


    window.requestAnimationFrame = (function() {
        return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(callback) {
                window.setTimeout(callback, 1000 / 60);
            };
    })();
};

حالا سه توپ داریم ، سمت چپی بنفش است و دیرتر می افتد ، وسطی قرمز است و سقوط می کند. سمت راستی قرمز است ، اولش کمی می رود بالا ، بعدش سقوط می کند.
 

جدیدترین ارسال ها

بالا