0

I need these images rendered in html5 canvas to be centered, rotated and resized depending on the size of the bounding box. I managed to rotate and resize the images but they are not centered anymore.

Can someone help me to fit these images in bounds and keep them in the center of the boxes? (fiddle updated)

http://jsfiddle.net/owtwv1a5/6/

var renderSprite = function(img, x, y, width,height, degree, scale){

    var rads = degree * Math.PI/180;
    var heightRatio = height/img.height;
    var widthRatio  = width/img.width;

    var isRotated = (degree==90 || degree==270);

    if (isRotated) {
        var scale_ratio = height/img.width;
    } else {
        var scale_ratio = heightRatio;                                  
    }

    var scaledImgHeight = img.height*scale_ratio;
    var scaledImgWidth  = img.width*scale_ratio;
    var offsetX = width - scaledImgWidth;               

    if ((scaledImgHeight) < height) {
        y += parseInt((height-scaledImgHeight)/2);
        if (isRotated) {
            x -= (scaledImgWidth - scaledImgHeight) / 2;
        }
    }

    if ((scaledImgWidth) < width) {
        x += parseInt((width-scaledImgWidth)/2);
        if (isRotated) {
            x -= (scaledImgWidth - scaledImgHeight) / 2;
        }
    }   

    ctx.save();

    var centerX = x + scaledImgWidth * 0.5;
    var centerY = y + scaledImgHeight * 0.5;
    ctx.translate(centerX, centerY);

    ctx.rotate(rads);
    //ctx.scale(scale,scale);
    ctx.translate(-centerX, -centerY);

    ctx.drawImage(img, x,y, scaledImgWidth ,scaledImgHeight);
    ctx.restore();
 };
bluescreen
  • 117
  • 1
  • 6
  • Hello Bluescreen I have just ran your code and the image does rotate around its centre point. So you are rotating correctly however could you maybe explain your question a little clearer? I.E. should it be centred in the red box first then rotated? Should the red box be rotated with the image in it? – Canvas Sep 14 '15 at 12:27
  • Hi, I updated the fiddle: http://jsfiddle.net/owtwv1a5/5/ I need the images to be centered and fit into the boxes like this: http://i.stack.imgur.com/8G3Kh.png – bluescreen Sep 14 '15 at 12:36
  • possible duplicate of [HTML5 Canvas Rotate Image](http://stackoverflow.com/questions/17411991/html5-canvas-rotate-image) – GameAlchemist Sep 14 '15 at 12:40
  • There are many good answers about rotating images on S.O. Voting to close. (expl : http://stackoverflow.com/questions/17411991/html5-canvas-rotate-image see detailled @markE 's answer ) – GameAlchemist Sep 14 '15 at 12:41
  • No, this is not duplicated. I don't need to resize the canvas. I need to rotate and fit multiple images into several boxes on the same canvas. MarkE's example is a simple square. I need to fit rectangles. – bluescreen Sep 14 '15 at 12:49

0 Answers0