Advertisement
obernardovieira

Draw line on canvas using mouse

Feb 13th, 2017
460
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 0.84 KB | None | 0 0
  1. <!-- it uses fabric.js
  2. https://github.com/kangax/fabric.js/ -->
  3.  
  4.  
  5. <!-- html file -->
  6.  
  7. <canvas id="c" width="500" height="500" style="border:1px solid #ccc"></canvas>
  8.  
  9.  
  10.  
  11. <!-- js file -->
  12.  
  13. var canvas = new fabric.Canvas('c', { selection: false });
  14.  
  15. var line, isDown;
  16.  
  17. canvas.on('mouse:down', function(o){
  18.   isDown = true;
  19.   var pointer = canvas.getPointer(o.e);
  20.   var points = [ pointer.x, pointer.y, pointer.x, pointer.y ];
  21.   line = new fabric.Line(points, {
  22.     strokeWidth: 5,
  23.     fill: 'red',
  24.     stroke: 'red',
  25.     originX: 'center',
  26.     originY: 'center'
  27.   });
  28.   canvas.add(line);
  29. });
  30.  
  31. canvas.on('mouse:move', function(o){
  32.   if (!isDown) return;
  33.   var pointer = canvas.getPointer(o.e);
  34.   line.set({ x2: pointer.x, y2: pointer.y });
  35.   canvas.renderAll();
  36. });
  37.  
  38. canvas.on('mouse:up', function(o){
  39.   isDown = false;
  40. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement