其实,你的文字是由微小的1.0度旋转。
1 * Math.PI/180代表旋转
1种微小程度所以这将是一个非常突出的5度:
ctx.rotate(5.0 * Math.PI/180);
几个编码故障:
您需要增加旋转角度,让文字真实动画
angleInDegrees+=5;
ctx.rotate(angleInDegrees * Math.PI/180);
setInterval需要一个完整的函数作为参数,而不仅仅是一个函数的名称,如:
setInterval(function(){redraw();}, interval);
而这里的处理平移/旋转
相反未翻译和非旋转这样的简单的方法:
ctx.translate((200), (150));
ctx.rotate(1*Math.PI/180);
// draw stuff here
ctx.rotate(-(1*Math.PI/180));
ctx.translate(-(200), -(150));
可以改为context.save()和context.restore(),这是更清洁,不需要非这样做的:
// save the canvas context—including its un-translated and un-rotated setting
ctx.save();
ctx.translate(200,150);
ctx.rotate(angleInDegrees * Math.PI/180);
// draw stuff here
// after restore() the canvas is back to its starting position before save()
ctx.restore();
这里的代码和一个小提琴:http://jsfiddle.net/m1erickson/5XTcn/
<!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 canvasWidth;
var canvasHeight;
var interval = 350;
var angleInDegrees=0;
function init(){
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
canvasWidth = canvas.width;
canvasHeight = canvas.height;
setInterval(function(){redraw();}, interval);
}
init();
function redraw() {
angleInDegrees+=5;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.beginPath();
ctx.rect(200,150,5,5);
ctx.fill();
ctx.save();
ctx.translate(200,150);
ctx.rotate(angleInDegrees * Math.PI/180);
ctx.fillStyle = '#f00';
ctx.font = '40px san-serif';
ctx.textBaseline = 'top';
ctx.fillText("Hello rotated", 0, 0);
ctx.restore();
ctx.fillStyle = '#f00';
ctx.font = '40px san-serif';
ctx.textBaseline = 'top';
ctx.fillText("Hello still", 0, 0);
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=500 height=300></canvas>
</body>
</html>
非常感谢你,寻找答案和解释好! – poppel
以下语句为false:“setInterval需要一个完整的函数作为参数,而不仅仅是一个函数名称”。在原始代码中这可能看起来是正确的唯一原因是因为该函数在被引用之后被定义。 –