2012-08-16 37 views
1

我試圖創建一個動畫,其中畫布中間的圖像必須旋轉360度,同時保持其他對象畫布上的對象是固定的,基本上我想給像旋轉效果的粉絲,但它不適用於我的情況。遵循我正在使用的代碼片段。IN HTML5:如何將圖像旋轉到畫布中心的360度,並將其他對象固定爲平板

假定畫布大小是400由200

var surface; 
var img = new Image(); 
var angle = 0; 
img.src = "images/teddy.png"; 
surface = document.getElementById("canvas"); 
var ctx = surface.getContext('2d'); 

// Clear the canvas to White 
ctx .fillStyle = "rgb(255,255,255)"; 
ctx .fillRect(0, 0, surface.width, surface.height); 
// Save the current context 
ctx .save(); 
// Translate to the center point of our image 
ctx .translate(happy.width * 0.5, happy.height * 0.5); 
ctx .rotate(DegToRad(angle,surfaceContext)); //calling function here 
ctx .translate(-(happy.width * 0.5), -(happy.height * 0.5)); 
ctx .drawImage(happy, 200, 100); 
angle++; 
ctx.restore(); 

上面的代碼正在使用的setInterval(循環,10)調用;

它旋轉上的100像素直徑形象在現在的位置上爲200px x軸,但我想那是什麼形象應該保持其當前現在的位置旋轉

我是新來的HTML5,所以請容忍我:)

感謝 〜鑫馬

回答

2

我想這是你想要什麼: http://jsfiddle.net/zH9yy/

var render, loop, t, dt, 
    DEG2RAD = Math.PI/180, 
    cvs = document.querySelector('canvas'), 
    ctx = cvs.getContext('2d'), 
    teddy = new Image(), 
    heart = new Image(), 
    angle = 0, 
    reqAnimFrame = 
     window.requestAnimationFrame || 
     window.webkitRequestAnimationFrame || 
     window.mozRequestAnimationFrame || 
     window.msRequestAnimationFrame || 
     window.oRequestAnimationFrame; 

cvs.width = 400; 
cvs.height = 200; 

teddy.src = 'https://d3qcduphvv2yxi.cloudfront.net/assets/1204584/view_small/43b95bee9e4e9a8a1effcdc3d401774a.jpg'; 

heart.src = 'http://a.dryicons.com/files/graphics_previews/flower_heart.jpg'; 

render = function (timestamp) { 
    dt = timestamp - t; 
    t = timestamp; 

    // Clear the canvas to White 
    ctx.fillStyle = "rgb(255,255,255)"; 
    ctx.fillRect(0, 0, cvs.width, cvs.height); 

    // draw heart 
    ctx.drawImage(heart, -20, -120); 

    // draw teddy 
    ctx.save(); 
    ctx.translate(cvs.width/2, cvs.height/2); // move cursor to canvas center 
    ctx.rotate(DEG2RAD * angle); // rotate canvas 
    ctx.drawImage(teddy, -teddy.width/2, -teddy.height/2); // draw img center at cursor center 
    angle += dt/16.67 * 6; // increment angle ~ 360 deg/sec 
    ctx.restore(); 
}; 

loop = function (timestamp) { 
    reqAnimFrame(loop); 
    render(timestamp); 
}; 

t = Date.now(); 
loop(t); 

+1

是的確切這是(http://jsfiddle.net/zH9yy/)我想要什麼,但我正在尋找使用其他方式,而不需要「reqAnimFrame」。所以我設法以其他方式做到這一點。看看這個http://jsfiddle.net/p9GyW/ – Simer 2012-08-21 06:06:34