假设我有一个 40x40pxkineticjs 矩形,并且我还有一个包含 25 个 40x40 Sprite 的 200x200 spritesheet,并且我想为kineticjs 矩形提供其中一个单独 Sprite 的背景。我该怎么做这?
最佳答案
您可以定义自定义Kinetic.Shape
来显示剪辑的 Sprite 。
Kinetic.Shape
为您提供了一个包装的 Canvas 上下文,您可以在其上进行绘制,就像在 native Canvas 上绘制一样。包装的 Canvas 上下文具有 native Canvas 上下文的大部分(但不是全部)功能。
您可以使用 context.drawImage
的剪辑版本从 spritesheet 图像对象中剪辑 sprite,并将其绘制到自定义形状上。
然后使用 context.rect
在包含剪裁 Sprite 的 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 的形式 fork 了 KineticJS:http://konvajs.github.io/ 。我可以热情推荐 KonvaJS!
关于javascript - 从 spritesheet 定义kineticjs 矩形背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30220228/