Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h3>CENTER ACTIVE OBJECT IN VIEWPORT</h3>
Pan canvas to active object in a particular screen position.gjjku
<br />
<button id="pan1">Center-Center</button>
<button id="pan2">Center-Top</button>
<button id="pan3">Center-Bottom</button>
<div id="workarea">
  <canvas id="myCanvas" width="500" height="500"></canvas>
</div>
              
            
!

CSS

              
                #reset {
  background-color: blue;
  color: white;
  padding: 0.5em;
  margin: 0.5em;
  border: 0;
}

#workarea {
  display: flex;
}

#sidebar {
  min-width: 200px;
  background-color: black;
}
              
            
!

JS

              
                const canvas = new fabric.Canvas("myCanvas")
canvas.backgroundColor="#999999"

const lastX = null
const lastY = null

var centerLineHori = new fabric.Line([0, 0, 0, canvas.getHeight()], {
        left: canvas.getWidth() /2 ,
        top: 0,
        stroke: 'red',
        selectable: false,
        evented: false
    })

var centerLineVert = new fabric.Line([canvas.getWidth(), 0, 0, 0], {
        left: 0,
        top: canvas.getHeight() /2,
        stroke: 'red',
        selectable: false,
        evented: false
    })

var movingBox = new fabric.Rect ({
  width: 450,
  height: 300,
  top: 20,
  left: 50,
  fill: 'purple',
  id: "myBox"
})

var box2 = new fabric.Rect ({
  width: 200,
  height: 200,
  fill: 'green',
})

canvas.add(movingBox)
canvas.add(box2)
canvas.add(centerLineHori)
canvas.add(centerLineVert)

document.getElementById('pan1').addEventListener('click', function() {
  panToActiveObject('center-center')
}, false)

document.getElementById('pan2').addEventListener('click', function() {
  panToActiveObject('center-top')
}, false)

document.getElementById('pan3').addEventListener('click', function() {
  panToActiveObject('center-bottom')
}, false)

canvas.setActiveObject(canvas.item(0))


// ==========================================
// PAN FUNCTION
// ==========================================
function panToActiveObject(position) {
  
  // Pan the entire canvas so that the active object is centered in the viewport.
  // The object's relative position in the canvas should not change.
 
  let object = canvas.getActiveObject()
  let objWidth = object.getScaledWidth()
  let objHeight = object.getScaledHeight()
  let zoom = canvas.getZoom()
  let panX = 0
  let panY = 0
  
 
  console.log("object width is: " + object.width)
   console.log(" object.getScaledWidth.x is: " + object.getScaledWidth())
  
  // WORKS - setViewportTransform
  panX = ((canvas.getWidth() / zoom / 2) - (object.aCoords.tl.x) - (objWidth / 2)) * zoom
  
  if(!position || position == 'center-center') {
    
    panY = ((canvas.getHeight() / zoom / 2) - (object.aCoords.tl.y) - (objHeight / 2)) * zoom
    
  } else if (position == 'center-top') {
    
    panY = (-object.aCoords.tl.y + 50) * zoom
    
  } else if (position == 'center-bottom') {

    panY = ((canvas.getHeight() / zoom) - (object.aCoords.tl.y) - (objHeight + 50)) * zoom
    
  }
   
   canvas.setViewportTransform([zoom, 0, 0, zoom, panX, panY])
  
  // ALSO WORKS - (for center/center) relative pan
  /*
  panX = (canvas.getVpCenter().x - object.getCenterPoint().x) * zoom
  panY =  ((canvas.getVpCenter().y - object.getCenterPoint().y) * zoom)
 canvas.relativePan({x:panX, y:panY})
  */
 // canvas.requestRenderAll()
  //canvas.calcCoords
  
  centerGuidelines()
}

function centerGuidelines() {
   centerLineHori.viewportCenter()
  centerLineHori.setCoords()
centerLineVert.viewportCenter()
centerLineVert.setCoords()
}



canvas.on({


            'object:modified': (event) => {
              console.log("setCoords")
               //event.target.setCoords
               //canvas.getActiveObject.setCoords
            },


})


// ==========================================
// INTERACTIONS
// ==========================================


// MOUSEWHEEL ZOOM
canvas.on({
  
   'mouse:down': (opt) => {
     
     console.log("mouse down")
    
    // Capture mouse coords for mousewheel-zoom-to-cursor
    this.lastX = opt.pointer.x
    this.lastY = opt.pointer.y     
  },
  
  'mouse:wheel': (opt) => {
  let delta = 0
  
  // -------------------------------
  // WHEEL RESOLUTION
  let wheelDelta = opt.e.wheelDelta
  let deltaY = opt.e.deltaY

  // CHROME WIN/MAC | SAFARI 7 MAC | OPERA WIN/MAC | EDGE
  if (wheelDelta) {
    delta = -wheelDelta / 120
  }
  // FIREFOX WIN / MAC | IE
  if(deltaY) {
    deltaY > 0 ? delta = 1 : delta = -1
  }
  // -------------------------------
  
  let pointer = canvas.getPointer(opt.e)
  let zoom = canvas.getZoom()
  zoom = zoom - delta / 10

  // limit zoom in
  if (zoom > 4) zoom = 4

  // limit zoom out
  if (zoom < 0.2) {
    zoom = 0.2
  }

  //canvas.zoomToPoint({
  //  x: opt.e.offsetX,
  //  y: opt.e.offsetY
  //}, zoom)
  
  canvas.zoomToPoint(
    new fabric.Point(canvas.width / 2, canvas.height / 2),
    zoom);

  opt.e.preventDefault()
  opt.e.stopPropagation() 

  canvas.renderAll()
  canvas.calcOffset()
    
  },
  
  'touch:drag': (opt) => {
    
    console.log("drag pan")
    
    // For panning (click and drag)
    
    if(canvas.getActiveObject() == null) {
    
      let startX = opt.self.start.x
      let startY = opt.self.start.y
      let currentX = opt.self.x
      let currentY = opt.self.y
      let xChange = currentX - this.lastX
      let yChange = currentY - this.lastY      
      let delta = new fabric.Point(xChange, yChange)

      console.log("canvas.getCenter.top: " + canvas.getCenter().top)
      console.log("canvas.getVpCenter.y: " + canvas.getVpCenter().y)

      canvas.relativePan(delta)
      canvas.requestRenderAll()
      this.lastX = currentX
      this.lastY = currentY
      centerGuidelines()
    }
  }

})

              
            
!
999px

Console