HTML5 Game - Linear Interpolation(lerp)

Introduction

The code equation is used to work out the next point of the interpolation.

n = start + (end - start) * speed 
 

Demo

ResultView the demo in separate window

<!doctype html>
<html lang="en">
<body>
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvas" width="500" height="500">
 Your browser does not support the HTML 5 Canvas. 
</canvas>// w w  w  . j  a v a2s .co  m
<script type="text/javascript">
  let ele = document.getElementById('canvas');
    let ctx = ele.getContext('2d');

let startX = 10; 
let startY = 10; 
let endX = ele.width - 50; 

let x = startX; 
let y = startY; 
let duration = 0; 
let width = height = 50; 
  
function lerp(start, end, speed) { 
    return start + (end - start) * speed; 
} 
  
function logic () { 
    duration += 0.02; 
    x = lerp(startX, endX, duration); 
    if (x < ele.width - width) 
        requestAnimationFrame(draw); 
} 
  
function draw()  { 
    ctx.clearRect(0, 0, ele.width, ele.height); 
      
    ctx.fillStyle = "#ff0000"; 
  
    ctx.fillRect(x, y, 50, 50); 
} 
requestAnimationFrame(draw); 
setInterval(logic, 1000/60); 

</script> 
</div>
</body>
</html>

Related Topic