Search code examples
javascripthtmlrotationkineticjs

Rotates when I scramble Kineticjs


i have scrambled my puzzzle, now i need to have it rotated when i scrmable? can anyone help? Thanks :)

    fillPatternImage:imageObj,
                    x:-pieceWidth*i/2,
                    y:-pieceHeight*j/2,
                    stroke: "#000000",
                    strokeWidth: 4,
                    lineCap: "round",
                    draggable: true,
                x: i+pieceWidth/4 + (Math.random()*4)*((stage.getWidth()+pieceWidth)/12),
                y: j+pieceHeight/4 + (Math.random()*2)*((stage.getHeight()+pieceHeight)/12),
            });

JsFiddle : http://jsfiddle.net/vFez6/25/


Solution

  • The general method to rotate a canvas drawing is:

    • save the context state: context.save()
    • translate to the desired center of the object: context.translate(centerX,centerY)
    • rotate by the desired radian angle: context.rotate(Math.PI/4)
    • draw the object offset by 1/2 width & height: 'context.fillRect(-width/2,-height/2,50,30)'
    • restore the context state to its unrotated state: 'context.restore()'

    enter image description here

    Example code and a Demo: http://jsfiddle.net/m1erickson/7aqwjddt/

    rotateRectangle(150,150,75,50,45*Math.PI/180);
    
    function rotateRectangle(centerX,centerY,width,height,radianAngle){
        ctx.save();
        ctx.translate(centerX,centerY);
        ctx.rotate(radianAngle);
        ctx.fillRect(-width/2,-height/2,width,height);
        ctx.restore();
    }