Search code examples
javascriptfabricjs

JavaScript - Dynamically create SVG and modify for cursor


Say I have a HTML5 canvas (In this case using fabric.js), and I want to change the cursor over the canvas to represent whatever brush size and colour has been selected. I'm thinking there should be a way to do this by changing an SVG's properties (size & colour) dynamically with JS so we don't have to use multiple images. Any ideas on if this is possible?

var canvas = new fabric.Canvas(c, {
            isDrawingMode: true,
            freeDrawingCursor: 'url("img/cursor.svg"), auto'
});

Solution

  • I think freeDrawingCursor is just looking for normal css property names. Here is an example of how to have a fabric object represent the cursor size and color:

    var canvas = new fabric.Canvas('c', {
      isDrawingMode: true,
      freeDrawingCursor: 'none'
    });
    
    canvas.freeDrawingBrush.width = 10;
    canvas.freeDrawingBrush.color = '#9f9';
    
    var mousecursor = new fabric.Circle({ 
      left: 0, 
      top: 0, 
      radius: canvas.freeDrawingBrush.width / 2, 
      fill: canvas.freeDrawingBrush.color, 
      originX: 'right', 
      originY: 'bottom',
    })
    
    canvas.add(mousecursor);
    
    canvas.on('mouse:move', function(obj) {
      mousecursor.top = obj.e.y - mousecursor.radius;
      mousecursor.left = obj.e.x - mousecursor.radius;
      canvas.renderAll()
    })
    
    canvas.on('mouse:out', function(obj) {
      // put circle off screen
      mousecursor.top = -100;
      mousecursor.left = -100;
      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>