Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Raphael JS, fill an SVG element with with a background-image with an offset

I want to this this Fill SVG element with with a background-image with an offset, but using Raphael JS.

Displaying an rectangle with a background image without the offset is easy.

canvas.rect(
    positionx, positiony, width, height
).attr(
    {fill: "url('/content/image_set.gif')"}
);

The code above will display only the upper-left corner of the image. I want to shift it and display another part of it. How can I do it?

like image 303
jpbochi Avatar asked Mar 21 '11 13:03

jpbochi


1 Answers

I'd suggest drawing the image separately from the rect. If you need the stroke you can either draw a filled rect behind the image or draw the rect on top with stroke and no fill.

The image is drawn with clipping to clip out the part you want, and you can control the offset of the image either with img.translate(x,y) or by the paper.image params:

var img = paper.image("foo.png", 10, 10, 80, 80);
img.attr({ "clip-rect": "20,20,30,30" });

This above works only for rectangular clipping (svg itself supports arbitrary clipping via the 'clip-path' property). If you want a pattern fill, then you currently have to step outside of what raphaël provides. Easiest is probably to just extend raphaël to do that, and to provide some other fallback to the browser(s) that doesn't support svg.

SVG Web seems to have at least partial support for svg patterns if you're looking for something to work as a fallback for old browsers.

like image 71
Erik Dahlström Avatar answered Nov 08 '22 18:11

Erik Dahlström