从spritesheet定义kineticjs rect背景

时间:2015-05-13 16:14:52

标签: javascript jquery html5 kineticjs

鉴于我有一个40x40px的kineticjs rect,我也有一个200x200 spritesheet包含25个40x40精灵,我想给kineticjs rect一个单独精灵的背景..我怎么会这样做这个?

1 个答案:

答案 0 :(得分:1)

您可以定义自定义Kinetic.Shape以显示剪切的精灵。

Kinetic.Shape为您提供了一个包装的画布上下文,可以在其上绘制,就像在本机画布上绘制一样。包装的画布上下文具有本机画布上下文的大部分功能,但不是全部功能。

您可以使用剪裁版本的context.drawImage剪切spritesheet图像对象中的精灵,并将其绘制到自定义形状上。

然后使用context.rect在包含剪切精灵的Kinetic.Shape周围绘制一条描边边框。

以下是示例代码和演示:

    var stage = new Kinetic.Stage({
        container: 'container',
        width: 350,
        height: 350
    });
    var layer = new Kinetic.Layer();
    stage.add(layer);

    // ??? Fix very wierd glitch!
    // The Kinetic.Shape is not cleared if it's the only element on the canvas
    layer.add(new Kinetic.Circle({x:-300,y:250,radius:25,fill:'red'}));
    layer.draw();

var spriteRect;
var sw=471/5;
var sh=255/2;

var spritesheet=new Image();
spritesheet.crossOrigin='anonymous';
spritesheet.onload=start;
spritesheet.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/avatars.png";
function start(){

    spriteRect = new Kinetic.Shape({
        x: 20,
        y: 30,
        stroke:'black',
        strokeWidth:3,
        draggable:true,
        drawFunc: function(ctx) {
          // clip a sprite from the spritesheet and draw it on spriteRect
          ctx.drawImage(spritesheet, sw*1,0,sw,sh, 0,0,sw,sh);
          // draw a stroked border around the image
          ctx.rect(0,0,sw,sh);
          // tell KineticJS to draw the image + border on the layer
          ctx.fillStrokeShape(this);
        }
    });
    layer.add(spriteRect);
    layer.draw();   


}
body{padding:20px;}
#container{
  border:solid 1px #ccc;
  margin-top: 10px;
  width:350px;
  height:350px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/kineticjs/5.2.0/kinetic.min.js"></script>
<h4>A draggable sprite-rect.</h4>
<div id="container"></div>
<h4>The spritesheet image</h4>
<img cross-origin=anonymous src='https://dl.dropboxusercontent.com/u/139992952/stackoverflow/avatars.png'>

顺便说一句,KineticJS已经退役,但Stackoverflow成员@lavrton以KonvaJS的形式分配了KineticJS:http://konvajs.github.io/。我可以热情地推荐KonvaJS!