Search code examples
htmlcanvashtml5-canvascreatejs

Spinning Wheel with HTML 5 canvas


Im trying to get these 2 png images to simply rotate on my canvas. The images are larger than the canvas because I only want to show certain sections of the wheel as it rotates into the canvas. I got the pngs perfectly on the canvas, they are circular and aligned to the bottom and centered so that it only shows that section of the wheel. Im using createjs in my code with easl and tween. For some reason when I rotate my image, it does it from some random registration point. Is there a way I can get this image to rotate around its own center which is off the canvas area?

var CANVAS;
var STAGE;
var CTX;

var imageCount = 0;

var img1Obj = new Image();
var img2Obj = new Image();
var img3Obj = new Image();

var img1;
var img2;
var img3;

var box;

function init(){

    CANVAS  = document.getElementById("spinWheel");
    STAGE   = new createjs.Stage(CANVAS);
    CTX     = CANVAS.getContext('2d');  

    img1Obj.src = "img/iphone_wheel_outer.png";
    img2Obj.src = "img/iphone_wheel_middle.png";
    img3Obj.src = "img/iphone_wheel_inner.png";

    img1Obj.name = "img1";
    img2Obj.name = "img2";
    img3Obj.name = "img3";

    img1Obj.onload = loadImages;
    img2Obj.onload = loadImages;
    img3Obj.onload = loadImages;

    createjs.Ticker.setFPS(30);
    createjs.Ticker.addListener(STAGE);

}


function loadImages(e)
{
    if(e.target.name == 'img1'){img1 = new createjs.Bitmap(img1Obj); }
    if(e.target.name == 'img2'){img2 = new createjs.Bitmap(img2Obj); }
    if(e.target.name == 'img3'){img3 = new createjs.Bitmap(img3Obj); }

    imageCount++;

    /* Display graphics until all of them are loaded */

    if(imageCount == 3)
    {
        buildInterface();
    }
}

function buildInterface(){


    img1.x = -370;
    img2.x = -370;
    img3.x = -370;

    img1.y = 235;
    img2.y = 235;
    img3.y = 235;

    createjs.Tween.get(img1,{loop:true})
            .to({rotation : 360}, 2000);


    STAGE.addChild(img1, img2, img3, box);

}

$(document).ready(function() {
    init();
}); 

Solution

  • I finally figured it out.

    The answers on here telling me to rotate the context are not wrong it just doesnt work if Im using createjs.Bitmap to generate images in canvas. However, it is actually a lot simpler by using createjs libraries. All I have to do is:

    img1.regX   = img1.image.width/2|0;
    img1.regY   = img1.image.height/2|0;
    

    This actually targets the registration point of the bitmap directly, no need for me to manipulate the context since the createjs.Bitmap object takes care of this internally for me.

    Thanks for the help anyways!