1

我正在尝试创建一个动画,其中画布中间的图像必须旋转 360 度,同时保持画布上的其他对象静止,基本上我想给图像提供类似风扇的旋转效果,但它不起作用我的情况。按照我正在使用的代码片段。

假设画布大小为 400 x 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(loop, 10); 调用的。

它在 x 轴上 200px 的位置上以 100px 的直径旋转图像,但我想要的是图像应该继续在其当前位置旋转

我是 HTML5 新手,所以请耐心等待 :)

谢谢~西默

4

1 回答 1

3

我假设这就是你想要的: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);

​</p>

于 2012-08-16T15:51:12.463 回答