Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

javascript - Lasso tool in html5 canvas

I'm trying to build a freeform lasso tool to clip an image inside canvas. I'm using fabric.js to draw the shape.

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');

img.onload = function() {
  var OwnCanv = new fabric.Canvas('c', {
    isDrawingMode: true
  });

  OwnCanv.freeDrawingBrush.color = "purple"
  OwnCanv.freeDrawingBrush.width = 4

  ctx.clip();

  ctx.drawImage(img, 0, 0);
}

img.src = "http://upload.wikimedia.org/wikipedia/commons/3/33/Jbassette4.jpg?uselang=fi";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>

<canvas id="c" width="500" height="500"></canvas>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The image needs to be a fabric.Image.

You could try something like this:

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');

img.onload = function() {
    var OwnCanv = new fabric.Canvas('c', {
        isDrawingMode: true
    });

    var imgInstance = new fabric.Image(img, {
        left: 0,
        top: 0,
    });
    OwnCanv.add(imgInstance);

    OwnCanv.freeDrawingBrush.color = "purple"
    OwnCanv.freeDrawingBrush.width = 4

    OwnCanv.on('path:created', function(options) {
        var path = options.path;
        OwnCanv.isDrawingMode = false;
        OwnCanv.remove(imgInstance);
        OwnCanv.remove(path);
        OwnCanv.clipTo = function(ctx) {
            path.render(ctx);
        };
        OwnCanv.add(imgInstance);
    });
}

img.src = "http://upload.wikimedia.org/wikipedia/commons/3/33/Jbassette4.jpg?uselang=fi";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>

<canvas id="c" width="500" height="500"></canvas>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...