简体   繁体   中英

fabric.js: How to clip my number or alphabet sprite?

sprite.png

I have a sprite(36hx360w) of numbers, and I want to clip it to 0, 1, 2, ..., 9, making 10 fabric.Image objects, whose width is 36px and height is 36px. 精灵

This is how I've tried, but it doesn't work as I expected.

fabric.Image.fromURL(my_sprite, function(img) {
  canvas.add(img);
  canvas.renderAll();
},{
  width:360,
  height:36,
  top:0,
  left:0,
  clipTo:function(ctx){
    ctx.rect(0,0,36,36);
  }
});

Here is the jsfiddle link: https://jsfiddle.net/fLh5a7k9/

As per comments:

Rewrite your code like this:

(function() {
    var canvas = this.__canvas = new fabric.Canvas('c');
    for (i = 0; i < 10; i++) { 
        drawRect(canvas, i);
    }
    canvas.renderAll();
})();

function drawRect(canvas, i){    
        fabric.Image.fromURL('http://i.stack.imgur.com/aGOgp.png', function(img) {
        canvas.add(img);  
    },{
        width:360,
        height:36,
        top: 36 * i,
        left: -( 36 * i ),
        clipTo:function(ctx){
            ctx.rect(-180 + 36 * i, -18 , 36, 36);
    }
});

Working fiddle: http://jsfiddle.net/ZxYCP/172/

You can use the fabric.Sprite.fromURL which lets you create sprites from fabric.js. It will also offer other helpers for creating and managing sprites

See more details in http://fabricjs.com/animated-sprite/

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