canvas绘制动画球,并通过鼠标交互移动

已被阅读 1888 次 | 文章分类:javascript | 2019-03-22 10:02

本例中通过简单的线性插值,规划小球的跟随鼠标的移动轨迹

一:动画原理

1、基本思路是:绘制一个球,然后定义球的起始和结束位置,然后不断更新球的位置,直到球到达指定位置,那么在这个过渡过程中,需要循环执行的一个函数,该函数不断插值得到一个新的位置,实时更新球的位置

2、循环执行的方式使用requestAnimationFrame(),线性插值函数如下:

                                            
function lerp(min, max, fraction) {
    return (max - min) * fraction + min;
}
                                            
                                        

lerp一般性的线性插值方法,从一个位置到另一个位置的过渡效果,fraction缓动因子越小,过度更平滑

二:全部代码

全部代码

                                            
//初始化canvas
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const width = canvas.width = window.innerWidth;
const height = canvas.height = window.innerHeight;
var x = 60,
    y = 60,
    endX = 100,
    endY = 160;

update();
// 将事件换成 mousemove尝试
canvas.addEventListener('click', function (e) {
    endX = e.offsetX;
    endY = e.offsetY;
    update();

})
// 绘制球
function drawBall(x, y, radius) {
    context.beginPath();
    context.fillStyle = '#66da79';
    context.arc(x, y, radius, 0, Math.PI * 2, false);
    context.fill();
}
// 更新位置
function update() {
    context.clearRect(0, 0, width, height);
    drawBall(x, y, 30);
    x = lerp(x, endX, 0.01);
    y = lerp(y, endY, 0.01);
    var loop = requestAnimationFrame(update);
    if (Math.abs(x - endX) < 0.0005 && Math.abs(y - endY) < 0.0005) {
        window.cancelAnimationFrame(loop);
    }
}
// 线性插值
function lerp(min, max, fraction) {
    return (max - min) * fraction + min;
}
                                            
                                        

线性插值是在一个方向插值,所以对x方向和y方向,分别进行一次插值

三:演示效果

/net/upload/image/20190322/6371083175625417463026850.gif

QQ:3410192267 | 技术支持 微信:popstarqqsmall

Copyright ©2017 xiaobaigis.com . 版权所有 鲁ICP备17027716号