在画布

时间:2015-09-14 12:19:29

标签: html5-canvas

我需要在html5画布中渲染这些图像,使其居中,旋转并调整大小,具体取决于边界框的大小。我设法旋转并调整图像大小,但它们不再居中。

有人可以帮助我将这些图像放入边界并将它们放在盒子的中央吗? (小提琴更新)

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();
 };

0 个答案:

没有答案
相关问题