Dec 10, 2017

Using SVG.js to clip an image sprite

Let's say you have an image with few sprites in it (such as Star Trek: Starships by Corey Marion):


Let's also say you are using a SVG javascript library such as svgjs to build dynamic images and animations. You want to overlay an icon sprite on top of your existing image. To do this you use the following code:


var col = {
    x: 0,
    y: 0,
}
var draw = SVG('drawing2').size(300, 300)
var clip = draw.clip()
var rect = draw.rect(32, 32)
var image = draw
    .image('http://icons.iconarchive.com/icons/iconfactory/star-trek-ships/icons-390.jpg')
    .move(-1*(32+5)*col.x-5,-1*(32+5)*col.y-5)
clip.add(rect)

image.clipWith(clip)

An explanation of the code:
  • The col object stores the row and column coordinates for the icon we want. We have 9 columns and 6 rows to work with.
  • The draw object takes our HTML div object and uses it to make our SVG
  • The clip object is where the magic happens
  • The rect object is a standard rectangle, which is going to be used as our 'frame' to cut out our desired sprite using clip. It is 32x32 pixels because that is the size of our icons.
  • The image object is our compiled sprites, but note that we 'move' it relative to the rectangle  using an algorithm. This 'move' allows us to align our desired sprite so that is with the rectangle.
  • The next two lines allows us to 'clip' the image with the rectangle, cutting away everything else except for our desired sprite.
The next example expands upon the above, but now allows us to place our rect (and our sprite) at a desired point on the drawing.


var col = {
    x: 8,
    y: 1,
}
var pos = {
    x: 32,
    y: 32
}
var draw = SVG('drawing2').size(300, 300)
var clip = draw.clip()
var rect = draw.rect(32, 32).move(pos.x, pos.y)
var image = draw
    .image('http://icons.iconarchive.com/icons/iconfactory/star-trek-ships/icons-390.jpg')
    .move(-1*(32+5)*col.x-5+pos.x,-1*(32+5)*col.y-5+pos.y)
clip.add(rect)


image.clipWith(clip)

No comments:

Post a Comment

Thanks for contributing!! Try to keep on topic and please avoid flame wars!!