HTML5 / js - how to animate straight line between two coordinates?

前端 未结 5 2271
你的背包
你的背包 2021-02-07 23:37

Simple enough question (could be wrong)

im looking to animate between two points in a straight line, using HTML5 and/or Jquery.

ctx.beginPath();
ctx.mov         


        
5条回答
  •  春和景丽
    2021-02-07 23:43

    You could use a linear interpolation or lerp. Something like this. Here is an example on jsfiddle: http://jsfiddle.net/UtmTh/ and here is the main code:

    var canvas = $("#paper")[0];
    var c = canvas.getContext("2d");
    
    var startX = 50;
    var startY = 50;
    var endX = 100;
    var endY = 100;
    var amount = 0;
    setInterval(function() {
        amount += 0.05; // change to alter duration
        if (amount > 1) amount = 1;
        c.clearRect(0, 0, canvas.width, canvas.height);
        c.strokeStyle = "black";
        c.moveTo(startX, startY);
        // lerp : a  + (b - a) * f
        c.lineTo(startX + (endX - startX) * amount, 
                 startY + (endY - startY) * amount);
        c.stroke();
    }, 30);​
    

提交回复
热议问题