How can I center an object horizontally with an animation?












1














I found the method centerH which puts the element correctly in the center



const activeElement = canvas.getActiveObject()
activeElement.centerH()


However it doesn't animate the object. So I tried to implement it myself



const activeElement = canvas.getActiveObject()

const { left, top } = canvas.getCenter();

const dest = {
left: left - activeElement.width / 2,
// top: top - activeElement.height / 2,
}

activeElement.animate(dest, {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease['easeOutCubic'],
duration: 500,
})


The problem here is that it doesn't work when the element is scaled and/or rotated.



Is there an easy way to create an animated centerH?



Code:






const fabric = window.fabric;

const canvas = new fabric.Canvas('canvas', {
background: 'silver',
centeredRotation: true,
})

canvas.setWidth(250)
canvas.setHeight(250)

const textbox = new fabric.Textbox('hello world this is', {
left: 5,
top: 200,
fontSize: 30,
hasRotatingPoint: false,
centeredScaling: true,
centeredRotation: true,
originX: 'left',
originY: 'top',
fixedWidth: 200,
width: 200,
angle: -75,
}).scale(0.65)
canvas.add(textbox).setActiveObject(textbox)

// grid
const gridStyle = {
stroke: 'red',
strokeWidth: 1,
selectable: false,
}
const center = {
h: canvas.width / 2,
v: canvas.height / 2,
}
const h = new fabric.Line([ center.h, 0, center.h, canvas.height], gridStyle)
const v = new fabric.Line([ 0, center.v, canvas.width, center.v], gridStyle)
canvas.add(h)
canvas.add(v)

// center function
document.getElementById('center').addEventListener('click', () => {
const activeElement = canvas.getActiveObject()

const { left, top } = canvas.getCenter()

const dest = {
left: left - activeElement.width / 2,
// top: top - activeElement.height / 2,
}

activeElement.animate(dest, {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease['easeOutCubic'],
duration: 500,
})
}, { passive: true })

body {
margin: 20px;
}

canvas {
border: 1px dashed red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.2/fabric.min.js"></script>
<button id="center">center element</button>
<br/>
<canvas id="canvas"></canvas>












share|improve this question






















  • I think first you must find rotation and scale factor, after that replace /2 part for centering... Becouse when you rotated to is not top and left is not left correctly.
    – kanpinar
    Nov 20 at 22:07
















1














I found the method centerH which puts the element correctly in the center



const activeElement = canvas.getActiveObject()
activeElement.centerH()


However it doesn't animate the object. So I tried to implement it myself



const activeElement = canvas.getActiveObject()

const { left, top } = canvas.getCenter();

const dest = {
left: left - activeElement.width / 2,
// top: top - activeElement.height / 2,
}

activeElement.animate(dest, {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease['easeOutCubic'],
duration: 500,
})


The problem here is that it doesn't work when the element is scaled and/or rotated.



Is there an easy way to create an animated centerH?



Code:






const fabric = window.fabric;

const canvas = new fabric.Canvas('canvas', {
background: 'silver',
centeredRotation: true,
})

canvas.setWidth(250)
canvas.setHeight(250)

const textbox = new fabric.Textbox('hello world this is', {
left: 5,
top: 200,
fontSize: 30,
hasRotatingPoint: false,
centeredScaling: true,
centeredRotation: true,
originX: 'left',
originY: 'top',
fixedWidth: 200,
width: 200,
angle: -75,
}).scale(0.65)
canvas.add(textbox).setActiveObject(textbox)

// grid
const gridStyle = {
stroke: 'red',
strokeWidth: 1,
selectable: false,
}
const center = {
h: canvas.width / 2,
v: canvas.height / 2,
}
const h = new fabric.Line([ center.h, 0, center.h, canvas.height], gridStyle)
const v = new fabric.Line([ 0, center.v, canvas.width, center.v], gridStyle)
canvas.add(h)
canvas.add(v)

// center function
document.getElementById('center').addEventListener('click', () => {
const activeElement = canvas.getActiveObject()

const { left, top } = canvas.getCenter()

const dest = {
left: left - activeElement.width / 2,
// top: top - activeElement.height / 2,
}

activeElement.animate(dest, {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease['easeOutCubic'],
duration: 500,
})
}, { passive: true })

body {
margin: 20px;
}

canvas {
border: 1px dashed red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.2/fabric.min.js"></script>
<button id="center">center element</button>
<br/>
<canvas id="canvas"></canvas>












share|improve this question






















  • I think first you must find rotation and scale factor, after that replace /2 part for centering... Becouse when you rotated to is not top and left is not left correctly.
    – kanpinar
    Nov 20 at 22:07














1












1








1







I found the method centerH which puts the element correctly in the center



const activeElement = canvas.getActiveObject()
activeElement.centerH()


However it doesn't animate the object. So I tried to implement it myself



const activeElement = canvas.getActiveObject()

const { left, top } = canvas.getCenter();

const dest = {
left: left - activeElement.width / 2,
// top: top - activeElement.height / 2,
}

activeElement.animate(dest, {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease['easeOutCubic'],
duration: 500,
})


The problem here is that it doesn't work when the element is scaled and/or rotated.



Is there an easy way to create an animated centerH?



Code:






const fabric = window.fabric;

const canvas = new fabric.Canvas('canvas', {
background: 'silver',
centeredRotation: true,
})

canvas.setWidth(250)
canvas.setHeight(250)

const textbox = new fabric.Textbox('hello world this is', {
left: 5,
top: 200,
fontSize: 30,
hasRotatingPoint: false,
centeredScaling: true,
centeredRotation: true,
originX: 'left',
originY: 'top',
fixedWidth: 200,
width: 200,
angle: -75,
}).scale(0.65)
canvas.add(textbox).setActiveObject(textbox)

// grid
const gridStyle = {
stroke: 'red',
strokeWidth: 1,
selectable: false,
}
const center = {
h: canvas.width / 2,
v: canvas.height / 2,
}
const h = new fabric.Line([ center.h, 0, center.h, canvas.height], gridStyle)
const v = new fabric.Line([ 0, center.v, canvas.width, center.v], gridStyle)
canvas.add(h)
canvas.add(v)

// center function
document.getElementById('center').addEventListener('click', () => {
const activeElement = canvas.getActiveObject()

const { left, top } = canvas.getCenter()

const dest = {
left: left - activeElement.width / 2,
// top: top - activeElement.height / 2,
}

activeElement.animate(dest, {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease['easeOutCubic'],
duration: 500,
})
}, { passive: true })

body {
margin: 20px;
}

canvas {
border: 1px dashed red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.2/fabric.min.js"></script>
<button id="center">center element</button>
<br/>
<canvas id="canvas"></canvas>












share|improve this question













I found the method centerH which puts the element correctly in the center



const activeElement = canvas.getActiveObject()
activeElement.centerH()


However it doesn't animate the object. So I tried to implement it myself



const activeElement = canvas.getActiveObject()

const { left, top } = canvas.getCenter();

const dest = {
left: left - activeElement.width / 2,
// top: top - activeElement.height / 2,
}

activeElement.animate(dest, {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease['easeOutCubic'],
duration: 500,
})


The problem here is that it doesn't work when the element is scaled and/or rotated.



Is there an easy way to create an animated centerH?



Code:






const fabric = window.fabric;

const canvas = new fabric.Canvas('canvas', {
background: 'silver',
centeredRotation: true,
})

canvas.setWidth(250)
canvas.setHeight(250)

const textbox = new fabric.Textbox('hello world this is', {
left: 5,
top: 200,
fontSize: 30,
hasRotatingPoint: false,
centeredScaling: true,
centeredRotation: true,
originX: 'left',
originY: 'top',
fixedWidth: 200,
width: 200,
angle: -75,
}).scale(0.65)
canvas.add(textbox).setActiveObject(textbox)

// grid
const gridStyle = {
stroke: 'red',
strokeWidth: 1,
selectable: false,
}
const center = {
h: canvas.width / 2,
v: canvas.height / 2,
}
const h = new fabric.Line([ center.h, 0, center.h, canvas.height], gridStyle)
const v = new fabric.Line([ 0, center.v, canvas.width, center.v], gridStyle)
canvas.add(h)
canvas.add(v)

// center function
document.getElementById('center').addEventListener('click', () => {
const activeElement = canvas.getActiveObject()

const { left, top } = canvas.getCenter()

const dest = {
left: left - activeElement.width / 2,
// top: top - activeElement.height / 2,
}

activeElement.animate(dest, {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease['easeOutCubic'],
duration: 500,
})
}, { passive: true })

body {
margin: 20px;
}

canvas {
border: 1px dashed red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.2/fabric.min.js"></script>
<button id="center">center element</button>
<br/>
<canvas id="canvas"></canvas>








const fabric = window.fabric;

const canvas = new fabric.Canvas('canvas', {
background: 'silver',
centeredRotation: true,
})

canvas.setWidth(250)
canvas.setHeight(250)

const textbox = new fabric.Textbox('hello world this is', {
left: 5,
top: 200,
fontSize: 30,
hasRotatingPoint: false,
centeredScaling: true,
centeredRotation: true,
originX: 'left',
originY: 'top',
fixedWidth: 200,
width: 200,
angle: -75,
}).scale(0.65)
canvas.add(textbox).setActiveObject(textbox)

// grid
const gridStyle = {
stroke: 'red',
strokeWidth: 1,
selectable: false,
}
const center = {
h: canvas.width / 2,
v: canvas.height / 2,
}
const h = new fabric.Line([ center.h, 0, center.h, canvas.height], gridStyle)
const v = new fabric.Line([ 0, center.v, canvas.width, center.v], gridStyle)
canvas.add(h)
canvas.add(v)

// center function
document.getElementById('center').addEventListener('click', () => {
const activeElement = canvas.getActiveObject()

const { left, top } = canvas.getCenter()

const dest = {
left: left - activeElement.width / 2,
// top: top - activeElement.height / 2,
}

activeElement.animate(dest, {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease['easeOutCubic'],
duration: 500,
})
}, { passive: true })

body {
margin: 20px;
}

canvas {
border: 1px dashed red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.2/fabric.min.js"></script>
<button id="center">center element</button>
<br/>
<canvas id="canvas"></canvas>





const fabric = window.fabric;

const canvas = new fabric.Canvas('canvas', {
background: 'silver',
centeredRotation: true,
})

canvas.setWidth(250)
canvas.setHeight(250)

const textbox = new fabric.Textbox('hello world this is', {
left: 5,
top: 200,
fontSize: 30,
hasRotatingPoint: false,
centeredScaling: true,
centeredRotation: true,
originX: 'left',
originY: 'top',
fixedWidth: 200,
width: 200,
angle: -75,
}).scale(0.65)
canvas.add(textbox).setActiveObject(textbox)

// grid
const gridStyle = {
stroke: 'red',
strokeWidth: 1,
selectable: false,
}
const center = {
h: canvas.width / 2,
v: canvas.height / 2,
}
const h = new fabric.Line([ center.h, 0, center.h, canvas.height], gridStyle)
const v = new fabric.Line([ 0, center.v, canvas.width, center.v], gridStyle)
canvas.add(h)
canvas.add(v)

// center function
document.getElementById('center').addEventListener('click', () => {
const activeElement = canvas.getActiveObject()

const { left, top } = canvas.getCenter()

const dest = {
left: left - activeElement.width / 2,
// top: top - activeElement.height / 2,
}

activeElement.animate(dest, {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease['easeOutCubic'],
duration: 500,
})
}, { passive: true })

body {
margin: 20px;
}

canvas {
border: 1px dashed red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.2/fabric.min.js"></script>
<button id="center">center element</button>
<br/>
<canvas id="canvas"></canvas>






javascript fabricjs fabricjs2






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 at 21:15









BrunoLM

59.2k65222382




59.2k65222382












  • I think first you must find rotation and scale factor, after that replace /2 part for centering... Becouse when you rotated to is not top and left is not left correctly.
    – kanpinar
    Nov 20 at 22:07


















  • I think first you must find rotation and scale factor, after that replace /2 part for centering... Becouse when you rotated to is not top and left is not left correctly.
    – kanpinar
    Nov 20 at 22:07
















I think first you must find rotation and scale factor, after that replace /2 part for centering... Becouse when you rotated to is not top and left is not left correctly.
– kanpinar
Nov 20 at 22:07




I think first you must find rotation and scale factor, after that replace /2 part for centering... Becouse when you rotated to is not top and left is not left correctly.
– kanpinar
Nov 20 at 22:07












1 Answer
1






active

oldest

votes


















1














From what I see, your task translates to




move the element to a position such that its center would be at the
canvas' center




Here's a function that does the calculations. Arguments x and y are the coordinates of the point on canvas; originX and originY describe which point of your element you want to be placed at x,y. The return value is a point whose coordinates you need to set as the object's left, top to have this position, taking into consideration object's origin.



function getPositionByOrigin (x, y, originX, originY) {
const point = new fabric.Point(x, y)
const center = this.translateToCenterPoint(point, originX, originY)
return this.translateToOriginPoint(center, this.originX, this.originY)
}


This is basically fabric.Object.prototype.setPositionByOrigin() but doesn't mutate the object immediately.



And here's a snippet:






const fabric = window.fabric;

const canvas = new fabric.Canvas('canvas', {
background: 'silver',
centeredRotation: true,
})

canvas.setWidth(250)
canvas.setHeight(250)

const textbox = new fabric.Textbox('hello world this is', {
left: 5,
top: 200,
fontSize: 30,
hasRotatingPoint: false,
centeredScaling: true,
centeredRotation: true,
originX: 'left',
originY: 'top',
fixedWidth: 200,
width: 200,
angle: -75,
}).scale(0.65)
canvas.add(textbox).setActiveObject(textbox)

// grid
const gridStyle = {
stroke: 'red',
strokeWidth: 1,
selectable: false,
}
const center = {
h: canvas.width / 2,
v: canvas.height / 2,
}
const h = new fabric.Line([ center.h, 0, center.h, canvas.height], gridStyle)
const v = new fabric.Line([ 0, center.v, canvas.width, center.v], gridStyle)
canvas.add(h)
canvas.add(v)

function getPositionByOrigin (x, y, originX, originY) {
const point = new fabric.Point(x, y)
const center = this.translateToCenterPoint(point, originX, originY)
return this.translateToOriginPoint(center, this.originX, this.originY)
}

// center function
document.getElementById('center').addEventListener('click', () => {
const activeElement = canvas.getActiveObject()

const { left, top } = canvas.getCenter()
const newPosition = getPositionByOrigin.call(activeElement, left, top, 'center', 'center')

const dest = {
left: newPosition.x,
top: newPosition.y
}

activeElement.animate(dest, {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease['easeOutCubic'],
duration: 500,
})
}, { passive: true })

body {
margin: 20px;
}

canvas {
border: 1px dashed red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.2/fabric.min.js"></script>
<button id="center">center element</button>
<br/>
<canvas id="canvas"></canvas>








share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401641%2fhow-can-i-center-an-object-horizontally-with-an-animation%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    From what I see, your task translates to




    move the element to a position such that its center would be at the
    canvas' center




    Here's a function that does the calculations. Arguments x and y are the coordinates of the point on canvas; originX and originY describe which point of your element you want to be placed at x,y. The return value is a point whose coordinates you need to set as the object's left, top to have this position, taking into consideration object's origin.



    function getPositionByOrigin (x, y, originX, originY) {
    const point = new fabric.Point(x, y)
    const center = this.translateToCenterPoint(point, originX, originY)
    return this.translateToOriginPoint(center, this.originX, this.originY)
    }


    This is basically fabric.Object.prototype.setPositionByOrigin() but doesn't mutate the object immediately.



    And here's a snippet:






    const fabric = window.fabric;

    const canvas = new fabric.Canvas('canvas', {
    background: 'silver',
    centeredRotation: true,
    })

    canvas.setWidth(250)
    canvas.setHeight(250)

    const textbox = new fabric.Textbox('hello world this is', {
    left: 5,
    top: 200,
    fontSize: 30,
    hasRotatingPoint: false,
    centeredScaling: true,
    centeredRotation: true,
    originX: 'left',
    originY: 'top',
    fixedWidth: 200,
    width: 200,
    angle: -75,
    }).scale(0.65)
    canvas.add(textbox).setActiveObject(textbox)

    // grid
    const gridStyle = {
    stroke: 'red',
    strokeWidth: 1,
    selectable: false,
    }
    const center = {
    h: canvas.width / 2,
    v: canvas.height / 2,
    }
    const h = new fabric.Line([ center.h, 0, center.h, canvas.height], gridStyle)
    const v = new fabric.Line([ 0, center.v, canvas.width, center.v], gridStyle)
    canvas.add(h)
    canvas.add(v)

    function getPositionByOrigin (x, y, originX, originY) {
    const point = new fabric.Point(x, y)
    const center = this.translateToCenterPoint(point, originX, originY)
    return this.translateToOriginPoint(center, this.originX, this.originY)
    }

    // center function
    document.getElementById('center').addEventListener('click', () => {
    const activeElement = canvas.getActiveObject()

    const { left, top } = canvas.getCenter()
    const newPosition = getPositionByOrigin.call(activeElement, left, top, 'center', 'center')

    const dest = {
    left: newPosition.x,
    top: newPosition.y
    }

    activeElement.animate(dest, {
    onChange: canvas.renderAll.bind(canvas),
    easing: fabric.util.ease['easeOutCubic'],
    duration: 500,
    })
    }, { passive: true })

    body {
    margin: 20px;
    }

    canvas {
    border: 1px dashed red;
    }

    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.2/fabric.min.js"></script>
    <button id="center">center element</button>
    <br/>
    <canvas id="canvas"></canvas>








    share|improve this answer


























      1














      From what I see, your task translates to




      move the element to a position such that its center would be at the
      canvas' center




      Here's a function that does the calculations. Arguments x and y are the coordinates of the point on canvas; originX and originY describe which point of your element you want to be placed at x,y. The return value is a point whose coordinates you need to set as the object's left, top to have this position, taking into consideration object's origin.



      function getPositionByOrigin (x, y, originX, originY) {
      const point = new fabric.Point(x, y)
      const center = this.translateToCenterPoint(point, originX, originY)
      return this.translateToOriginPoint(center, this.originX, this.originY)
      }


      This is basically fabric.Object.prototype.setPositionByOrigin() but doesn't mutate the object immediately.



      And here's a snippet:






      const fabric = window.fabric;

      const canvas = new fabric.Canvas('canvas', {
      background: 'silver',
      centeredRotation: true,
      })

      canvas.setWidth(250)
      canvas.setHeight(250)

      const textbox = new fabric.Textbox('hello world this is', {
      left: 5,
      top: 200,
      fontSize: 30,
      hasRotatingPoint: false,
      centeredScaling: true,
      centeredRotation: true,
      originX: 'left',
      originY: 'top',
      fixedWidth: 200,
      width: 200,
      angle: -75,
      }).scale(0.65)
      canvas.add(textbox).setActiveObject(textbox)

      // grid
      const gridStyle = {
      stroke: 'red',
      strokeWidth: 1,
      selectable: false,
      }
      const center = {
      h: canvas.width / 2,
      v: canvas.height / 2,
      }
      const h = new fabric.Line([ center.h, 0, center.h, canvas.height], gridStyle)
      const v = new fabric.Line([ 0, center.v, canvas.width, center.v], gridStyle)
      canvas.add(h)
      canvas.add(v)

      function getPositionByOrigin (x, y, originX, originY) {
      const point = new fabric.Point(x, y)
      const center = this.translateToCenterPoint(point, originX, originY)
      return this.translateToOriginPoint(center, this.originX, this.originY)
      }

      // center function
      document.getElementById('center').addEventListener('click', () => {
      const activeElement = canvas.getActiveObject()

      const { left, top } = canvas.getCenter()
      const newPosition = getPositionByOrigin.call(activeElement, left, top, 'center', 'center')

      const dest = {
      left: newPosition.x,
      top: newPosition.y
      }

      activeElement.animate(dest, {
      onChange: canvas.renderAll.bind(canvas),
      easing: fabric.util.ease['easeOutCubic'],
      duration: 500,
      })
      }, { passive: true })

      body {
      margin: 20px;
      }

      canvas {
      border: 1px dashed red;
      }

      <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.2/fabric.min.js"></script>
      <button id="center">center element</button>
      <br/>
      <canvas id="canvas"></canvas>








      share|improve this answer
























        1












        1








        1






        From what I see, your task translates to




        move the element to a position such that its center would be at the
        canvas' center




        Here's a function that does the calculations. Arguments x and y are the coordinates of the point on canvas; originX and originY describe which point of your element you want to be placed at x,y. The return value is a point whose coordinates you need to set as the object's left, top to have this position, taking into consideration object's origin.



        function getPositionByOrigin (x, y, originX, originY) {
        const point = new fabric.Point(x, y)
        const center = this.translateToCenterPoint(point, originX, originY)
        return this.translateToOriginPoint(center, this.originX, this.originY)
        }


        This is basically fabric.Object.prototype.setPositionByOrigin() but doesn't mutate the object immediately.



        And here's a snippet:






        const fabric = window.fabric;

        const canvas = new fabric.Canvas('canvas', {
        background: 'silver',
        centeredRotation: true,
        })

        canvas.setWidth(250)
        canvas.setHeight(250)

        const textbox = new fabric.Textbox('hello world this is', {
        left: 5,
        top: 200,
        fontSize: 30,
        hasRotatingPoint: false,
        centeredScaling: true,
        centeredRotation: true,
        originX: 'left',
        originY: 'top',
        fixedWidth: 200,
        width: 200,
        angle: -75,
        }).scale(0.65)
        canvas.add(textbox).setActiveObject(textbox)

        // grid
        const gridStyle = {
        stroke: 'red',
        strokeWidth: 1,
        selectable: false,
        }
        const center = {
        h: canvas.width / 2,
        v: canvas.height / 2,
        }
        const h = new fabric.Line([ center.h, 0, center.h, canvas.height], gridStyle)
        const v = new fabric.Line([ 0, center.v, canvas.width, center.v], gridStyle)
        canvas.add(h)
        canvas.add(v)

        function getPositionByOrigin (x, y, originX, originY) {
        const point = new fabric.Point(x, y)
        const center = this.translateToCenterPoint(point, originX, originY)
        return this.translateToOriginPoint(center, this.originX, this.originY)
        }

        // center function
        document.getElementById('center').addEventListener('click', () => {
        const activeElement = canvas.getActiveObject()

        const { left, top } = canvas.getCenter()
        const newPosition = getPositionByOrigin.call(activeElement, left, top, 'center', 'center')

        const dest = {
        left: newPosition.x,
        top: newPosition.y
        }

        activeElement.animate(dest, {
        onChange: canvas.renderAll.bind(canvas),
        easing: fabric.util.ease['easeOutCubic'],
        duration: 500,
        })
        }, { passive: true })

        body {
        margin: 20px;
        }

        canvas {
        border: 1px dashed red;
        }

        <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.2/fabric.min.js"></script>
        <button id="center">center element</button>
        <br/>
        <canvas id="canvas"></canvas>








        share|improve this answer












        From what I see, your task translates to




        move the element to a position such that its center would be at the
        canvas' center




        Here's a function that does the calculations. Arguments x and y are the coordinates of the point on canvas; originX and originY describe which point of your element you want to be placed at x,y. The return value is a point whose coordinates you need to set as the object's left, top to have this position, taking into consideration object's origin.



        function getPositionByOrigin (x, y, originX, originY) {
        const point = new fabric.Point(x, y)
        const center = this.translateToCenterPoint(point, originX, originY)
        return this.translateToOriginPoint(center, this.originX, this.originY)
        }


        This is basically fabric.Object.prototype.setPositionByOrigin() but doesn't mutate the object immediately.



        And here's a snippet:






        const fabric = window.fabric;

        const canvas = new fabric.Canvas('canvas', {
        background: 'silver',
        centeredRotation: true,
        })

        canvas.setWidth(250)
        canvas.setHeight(250)

        const textbox = new fabric.Textbox('hello world this is', {
        left: 5,
        top: 200,
        fontSize: 30,
        hasRotatingPoint: false,
        centeredScaling: true,
        centeredRotation: true,
        originX: 'left',
        originY: 'top',
        fixedWidth: 200,
        width: 200,
        angle: -75,
        }).scale(0.65)
        canvas.add(textbox).setActiveObject(textbox)

        // grid
        const gridStyle = {
        stroke: 'red',
        strokeWidth: 1,
        selectable: false,
        }
        const center = {
        h: canvas.width / 2,
        v: canvas.height / 2,
        }
        const h = new fabric.Line([ center.h, 0, center.h, canvas.height], gridStyle)
        const v = new fabric.Line([ 0, center.v, canvas.width, center.v], gridStyle)
        canvas.add(h)
        canvas.add(v)

        function getPositionByOrigin (x, y, originX, originY) {
        const point = new fabric.Point(x, y)
        const center = this.translateToCenterPoint(point, originX, originY)
        return this.translateToOriginPoint(center, this.originX, this.originY)
        }

        // center function
        document.getElementById('center').addEventListener('click', () => {
        const activeElement = canvas.getActiveObject()

        const { left, top } = canvas.getCenter()
        const newPosition = getPositionByOrigin.call(activeElement, left, top, 'center', 'center')

        const dest = {
        left: newPosition.x,
        top: newPosition.y
        }

        activeElement.animate(dest, {
        onChange: canvas.renderAll.bind(canvas),
        easing: fabric.util.ease['easeOutCubic'],
        duration: 500,
        })
        }, { passive: true })

        body {
        margin: 20px;
        }

        canvas {
        border: 1px dashed red;
        }

        <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.2/fabric.min.js"></script>
        <button id="center">center element</button>
        <br/>
        <canvas id="canvas"></canvas>








        const fabric = window.fabric;

        const canvas = new fabric.Canvas('canvas', {
        background: 'silver',
        centeredRotation: true,
        })

        canvas.setWidth(250)
        canvas.setHeight(250)

        const textbox = new fabric.Textbox('hello world this is', {
        left: 5,
        top: 200,
        fontSize: 30,
        hasRotatingPoint: false,
        centeredScaling: true,
        centeredRotation: true,
        originX: 'left',
        originY: 'top',
        fixedWidth: 200,
        width: 200,
        angle: -75,
        }).scale(0.65)
        canvas.add(textbox).setActiveObject(textbox)

        // grid
        const gridStyle = {
        stroke: 'red',
        strokeWidth: 1,
        selectable: false,
        }
        const center = {
        h: canvas.width / 2,
        v: canvas.height / 2,
        }
        const h = new fabric.Line([ center.h, 0, center.h, canvas.height], gridStyle)
        const v = new fabric.Line([ 0, center.v, canvas.width, center.v], gridStyle)
        canvas.add(h)
        canvas.add(v)

        function getPositionByOrigin (x, y, originX, originY) {
        const point = new fabric.Point(x, y)
        const center = this.translateToCenterPoint(point, originX, originY)
        return this.translateToOriginPoint(center, this.originX, this.originY)
        }

        // center function
        document.getElementById('center').addEventListener('click', () => {
        const activeElement = canvas.getActiveObject()

        const { left, top } = canvas.getCenter()
        const newPosition = getPositionByOrigin.call(activeElement, left, top, 'center', 'center')

        const dest = {
        left: newPosition.x,
        top: newPosition.y
        }

        activeElement.animate(dest, {
        onChange: canvas.renderAll.bind(canvas),
        easing: fabric.util.ease['easeOutCubic'],
        duration: 500,
        })
        }, { passive: true })

        body {
        margin: 20px;
        }

        canvas {
        border: 1px dashed red;
        }

        <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.2/fabric.min.js"></script>
        <button id="center">center element</button>
        <br/>
        <canvas id="canvas"></canvas>





        const fabric = window.fabric;

        const canvas = new fabric.Canvas('canvas', {
        background: 'silver',
        centeredRotation: true,
        })

        canvas.setWidth(250)
        canvas.setHeight(250)

        const textbox = new fabric.Textbox('hello world this is', {
        left: 5,
        top: 200,
        fontSize: 30,
        hasRotatingPoint: false,
        centeredScaling: true,
        centeredRotation: true,
        originX: 'left',
        originY: 'top',
        fixedWidth: 200,
        width: 200,
        angle: -75,
        }).scale(0.65)
        canvas.add(textbox).setActiveObject(textbox)

        // grid
        const gridStyle = {
        stroke: 'red',
        strokeWidth: 1,
        selectable: false,
        }
        const center = {
        h: canvas.width / 2,
        v: canvas.height / 2,
        }
        const h = new fabric.Line([ center.h, 0, center.h, canvas.height], gridStyle)
        const v = new fabric.Line([ 0, center.v, canvas.width, center.v], gridStyle)
        canvas.add(h)
        canvas.add(v)

        function getPositionByOrigin (x, y, originX, originY) {
        const point = new fabric.Point(x, y)
        const center = this.translateToCenterPoint(point, originX, originY)
        return this.translateToOriginPoint(center, this.originX, this.originY)
        }

        // center function
        document.getElementById('center').addEventListener('click', () => {
        const activeElement = canvas.getActiveObject()

        const { left, top } = canvas.getCenter()
        const newPosition = getPositionByOrigin.call(activeElement, left, top, 'center', 'center')

        const dest = {
        left: newPosition.x,
        top: newPosition.y
        }

        activeElement.animate(dest, {
        onChange: canvas.renderAll.bind(canvas),
        easing: fabric.util.ease['easeOutCubic'],
        duration: 500,
        })
        }, { passive: true })

        body {
        margin: 20px;
        }

        canvas {
        border: 1px dashed red;
        }

        <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.2/fabric.min.js"></script>
        <button id="center">center element</button>
        <br/>
        <canvas id="canvas"></canvas>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 at 23:13









        shkaper

        1,032514




        1,032514






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401641%2fhow-can-i-center-an-object-horizontally-with-an-animation%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Wiesbaden

            Marschland

            Dieringhausen