画布动画问题

问题描述:

我想旋转围绕画布中间的方块。但广场看起来是静态的。画布动画问题

// JScript source code 

var s_canvas; 
var s_context; 
var R = 70; 
var beta = 0; 
var Xs = R * Math.cos(beta); 
var Ys = R*Math.sin(beta); 
var WIDTH = 400; 
var HEIGHT = 300; 
var angle = 0; 
var tetha = 1.8 * Math.PI/180; 
var counterclockwise=true; 
var n = 4; 

function draw_square(c,n, x, y, r, angle, counterclockwise) { 

    c.fillStyle = "00ff00"; 
    c.beginPath(); 
    c.moveTo(x + r * Math.cos(angle), y - r * Math.sin(angle)); 

    var alpha=2*Math.PI/n; 

    for(var i=1;i<n;i++) 
    { 
     angle += alpha; 
     c.lineTo(x + r * Math.cos(angle), y - r * Math.sin(angle)); 
    } 
    c.closePath(); 

    c.fill(); 
} 

function clear_square() { 
    s_context.clearRect(0, 0, WIDTH, HEIGHT); 
} 

function init() { 
    s_canvas = document.getElementById("canvas_square"); 
    // Check if the canvas is supported and if the getContext is available 
    if (s_canvas && s_canvas.getContext) { 
     s_context = s_canvas.getContext("2d"); 
     return setInterval(draw, 10); 
    } 
    else { 
     alert("Canvas is not supported!"); 
    } 
} 

function draw() { 
    clear_square(); 
    s_context.save(); 
    s_context.translate(200, 150); 
    s_context.rotate(1.8 * Math.PI/180); 

    draw_square(s_context, n, Xs, Ys, 30, 0, true); 
    beta += tetha; 
    s_context.restore(); 


// Xs=R*Math.cos() 

} 

window.onload = init; 

首先,你可以取代你draw_square()从画布2D API

第二次尝试使用转换,而不是角度,您将得到更好的结果基本strokeRect()

这里是我的意思http://jsfiddle.net/austinbv/EP794/

一个的jsfiddle这里是我的JS这么

// Start the Canvas 
c = $('canvas').get(0).getContext('2d'); 

//Set the center 
c.translate(100,100) 


function drawAndRotate() { 
//Clear the canvas 
    c.clearRect(-100,-100,200,200) 
//draw a square 
    c.strokeRect(-25,-25,50,50) 
//rotate the canvas 
    c.rotate(0.017) 
    } 

//do it alot 
setInterval(drawAndRotate, 100) 

我知道这是不是真的调试你的代码,但它是一个更清洁的方式来获得相同的结果。

编辑:

我刚才看过了你的代码多一点,你需要设置的时间间隔尝试运行的最后一行window.onload.setInterval(init, 100)

+0

感谢。我找到了另一个解代码需要在context.save()之前设置旋转角度。 – miaf 2011-04-19 15:01:22

+0

你能分享你的解决方案Le_Bedel吗? (将其作为回答并验证它) – halflings 2013-04-23 22:37:56