Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

javascript - Rotate an image around its center in canvas

I'm trying to do my first image animation on canvas. I want the image to rotate but something is not correct in my code. Any ideas? This is all in a jquery document ready:

var canvas = document.getElementById('logobg1');  
    var ctx = canvas.getContext('2d');

    var img = new Image();   // Create new Image object
    img.src = 'images/containerbg.png'; // Set source path // set img src

    img.onload = function(){ // when image loads
        ctx.drawImage(img,0,0);
        setInterval(function() {
            ctx.save();
            ctx.clearRect(-ctx.canvas.width/2, -ctx.canvas.height/2, ctx.canvas.width, ctx.canvas.height);
            ctx.drawImage(img,0,0);
            ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2); // set canvas context to center
            ctx.rotate(Math.PI / 180 * 0.5); // 1/2 a degree
            ctx.restore();
        }, 16);
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

just change the order of your code, i.e.,

ctx.rotate(...);

ctx.drawImage(...);

See a working example http://jsbin.com/owuyiq/

$(function () {
    var canvas = document.getElementById('logobg1');
    var ctx = canvas.getContext('2d');
    var img = new Image();

    var ang = 0; //angle
    var fps = 1000 / 25; //number of frames per sec
    img.onload = function () { //on image load do the following stuff
        canvas.width = this.width << 1; //double the canvas width
        canvas.height = this.height << 1; //double the canvas height
        var cache = this; //cache the local copy of image element for future reference
        setInterval(function () {
            ctx.save(); //saves the state of canvas
            ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
            ctx.translate(cache.width, cache.height); //let's translate
            ctx.rotate(Math.PI / 180 * (ang += 5)); //increment the angle and rotate the image 
            ctx.drawImage(img, -cache.width / 2, -cache.height / 2, cache.width, cache.height); //draw the image ;)
            ctx.restore(); //restore the state of canvas
        }, fps);
    };

    img.src = 'http://i.stack.imgur.com/Z97wf.jpg?s=128'; //img
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...