在画布中旋转动画

时间:2017-03-15 23:04:30

标签: javascript animation canvas rotation html5-canvas

我试图打印" Buen trabajo"在画布上,让短语围绕中心原点旋转。我不确定该怎么做。我试图创建一个逐渐递增的循环,但我想我错过了一些东西。

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

function drawGoodJob(){
    var counter = 60;//so the object won't run for more than 60 seconds
    var increment = 10;//amount to increment the canvas by
    while(counter<60){
    ctx.rotate(increment*Math.PI/180);
    increment+20;
    }
drawGoodJob();
ctx.font = "80px Verdana";

// Create gradient
var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0", "magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "green");

// Fill with gradient
ctx.strokeStyle = gradient;
ctx.strokeText("Buen trabajo", 150, 400);//strokeText makes the letters hollow
}
</script>

1 个答案:

答案 0 :(得分:1)

我尝试过参考StackOverflow这篇文章。

HTML5 canvas animation and rotation

它可能与预期的不同,但它会有帮助吗?

<html>
<head>

</head>
<body>
<canvas id="testCanvas" width="800" height="600">

</canvas>

<script>
var rotation = 0;


(function init() {

    canvas = document.getElementById("testCanvas");
    context = canvas.getContext("2d");

    context.clearRect(0, 0, context.width, context.height);
    context.fillStyle = "lightblue";

    requestAnimationFrame(draw);

})();

function draw() {

    // reset transforms before clearing
    context.setTransform(1, 0, 0, 1, 0, 0);
    context.clearRect(0, 0, canvas.width, canvas.height);

    // tramslate and rotate an absolute rotation value
    context.translate(canvas.width/2, canvas.height/2);
    context.rotate(rotation);

    context.font = "80px Verdana";
    // Create gradient
    var gradient = context.createLinearGradient(0, 0, canvas.width, 0);
    gradient.addColorStop("0", "magenta");
    gradient.addColorStop("0.5", "blue");
    gradient.addColorStop("1.0", "green");

    // Fill with gradient
    context.strokeStyle = gradient;
    context.strokeText("Buen trabajo",-250, 0);//strokeText makes the letters hollow

    // update rotation value and request new frame
    rotation += 0.04;

    requestAnimationFrame(draw)
}

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