HTML5+JavaScript动画基础笔记

分类:JavaScript     发布时间:2016-10-16     最后更新:2019-12-07     浏览数:2081
HTML 5 动画基础笔记

从今天开始学习《HTML5+JavaScript动画基础》,看书写的练习代码全部托管在GitHub上,地址是https://github.com/PaytonTang/game

每天写一个例子。

2016-10-16:反弹

window.onload = function () {

 var canvas = document.getElementById("canvas"), // canvas dom 节点
        context = canvas.getContext("2d"), // canvas 2d 上下文
        ball = new Ball(), // 小球实例
        vx = Math.random() * 10 - 5, // x轴速度向量
        vy = Math.random() * 10 - 5, // y轴速度向量
        bounce = -0.8; // 反弹系数

    ball.x = canvas.width / 2; // 初始时小球在canvas的x轴中点
    ball.y = canvas.height / 2; // 初始时小球在canvas的y轴中点

    (function drawFrame () { // 帧函数,被重复调用
        window.requestAnimationFrame(drawFrame, canvas); // 重复调用帧函数
        context.clearRect(0, 0, canvas.width, canvas.height); // 先清除画布

        // 声明canvas画布的边界变量
        var left = 0,
            right = canvas.width,
            top = 0,
            bottom = canvas.height;

        // 小球的坐标改变,看起来小球就是做匀速运动
        ball.x += vx;
        // ball.y += vy;

        // 边界检测与处理
        if (ball.x + ball.radius > right) {
            ball.x = right - ball.radius;
            vx *= bounce;
        } else if (ball.x - ball.radius < left) {
            ball.x = left + ball.radius;
            vx *= bounce;
        }

        if (ball.y + ball.radius > bottom) {
            ball.y = bottom - ball.radius;
            vy *= bounce;
        } else if (ball.y - ball.radius < top) {
            ball.y = top + ball.radius;
            vy *= bounce;
        }

        ball.draw(context); // 重绘画布
    }());
}
上一篇: JavaScript 事件触发的两种方式 下一篇: Angular 2 学习资源