转换到画布中绘制的曲线?

时间:2013-06-11 18:08:02

标签: javascript canvas transition bezier

我有一条由贝塞尔曲线绘制的简单直线。挑战是改变它转换的位置,即如果曲线的高度增加或减少,它应该在转换中发生,而不是一下子。所以我的问题是提供画布鼠标悬停的过渡 - 如何提供到曲线的过渡?

canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d")
ctx.lineWidth = 6;
ctx.strokeStyle = "#333";
ctx.beginPath();
ctx.moveTo(328, 347);
ctx.bezierCurveTo(326, 387, 326, 386, 326, 420);
ctx.stroke();

1 个答案:

答案 0 :(得分:3)

您可以使用requestAnimationFrame为mouseenter上的曲线设置动画。

这是执行动画的功能:

现在,最佳做法正在转向使用requestAnimationFrame而不是setInterval。此代码将RAF包装在超时内,以控制帧速率。

function draw() {
    setTimeout(function() {

        // request another loop
        requestAnimationFrame(draw);

        // animate the control point
        cpY+=movement;
        if (cpY<50 || cpY>250){movement= -movement;}        

        // draw the new bezier
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.beginPath();
        ctx.moveTo(100,150);
        ctx.quadraticCurveTo(150,cpY,200,150);
        ctx.lineWidth=10;
        ctx.stroke();

    }, 1000 / fps);
}

这是代码和小提琴:http://jsfiddle.net/m1erickson/p5snk/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    var cpY = 150;
    var movement = -8;
    var fps = 60;

    $("#canvas").mouseenter(function () {
        cpY = 150;
        movement = -10;
        draw();
    });
    $("#canvas").mouseleave(function () {
        cpY = 50;
        movement = 15;
        draw();
    });

    drawLine();

    function drawLine() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.beginPath();
        ctx.moveTo(100, 150);
        ctx.lineTo(200, 150);
        ctx.lineWidth = 10;
        ctx.stroke();
    }

    function draw() {
        setTimeout(function () {

            if (cpY < 50) {
                return;
            }
            if (cpY > 150) {
                drawLine();
                return;
            }

            // request another loop
            requestAnimationFrame(draw);

            // animate the control point
            cpY += movement;

            // draw the new bezier
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.beginPath();
            ctx.moveTo(100, 150);
            ctx.quadraticCurveTo(150, cpY, 200, 150);
            ctx.lineWidth = 10;
            ctx.stroke();

        }, 1000 / fps);
    }

}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
相关问题