简体   繁体   中英

Fabric.js - Attach object creation to mouse click

When you create a new fabric object, you can specify the location for it to appear on the canvas. Is there a way to attach the generated object to the mouse and then place the object on click (or touch)?

Eg way to generate a circle which appears on the canvas.

var circle = new fabric.Circle({
  radius: 20, fill: 'green', left: 100, top: 100
});

It's fairly easy to update the position of an object to match that of the mouse's position and on mouse:up clone that object and place it on the canvas.

 var canvas = new fabric.Canvas('c'); var mousecursor = new fabric.Circle({ left: 0, top: 0, radius: 5, fill: '#9f9', originX: 'right', originY: 'bottom', }) canvas.add(mousecursor); canvas.on('mouse:move', function(obj) { mousecursor.top = obj.ey - mousecursor.radius; mousecursor.left = obj.ex - mousecursor.radius; canvas.renderAll() }) canvas.on('mouse:out', function(obj) { // put circle off screen mousecursor.top = -100; mousecursor.left = -100; canvas.renderAll() }) canvas.on('mouse:up', function(obj) { canvas.add(mousecursor.clone()) canvas.renderAll() }) 
 canvas { border: 1px solid #ccc; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.js"></script> <canvas id="c" width="600" height="600"></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM