简体   繁体   中英

Change color to image in js

I use this nice graph .

In

{"name":"Napoleon","group":1},

group needs to fill a color:

.style("fill", function(d) { return color(d.group); })

But if I want to save in group url (to image. So, I can see images in circles), how will be it looks like in html ?

Thanks!

In SVG you use a pattern to fill with an image then link to it. To keep your document 'data driven' and in the spirit of D3 you can set the pattern up like this in d3 (where urls is an array of image urls you are going to use).

d3.select('svg')
    .append('defs')
        .selectAll('pattern')
        .data(urls)
        .enter()
            .append('pattern')
                .attr({
                    'id': function(d, i){return 'my_pattern_' + i;},
                    'patternUnits':'userSpaceOnUse',
                    'width': dotSize,
                    'height': dotSize
                }).append('image')
                    .attr({
                        'xlink:href': function(d){return d;},
                        'x': 0,
                        'y': 0,
                        'width': dotSize,
                        'height': dotSize
                     })

Then when you want to use the image as a fill simply add the attribute to the relent object as

    .attr('fill', function(d, i){return 'url(#my_pattern_'+i+')'})

Of course, you will probably want to be able to map the exiting group to the relevant pattern id in the same way you can use color() to get the categories colour.


Here is a working example at JSFiddle which renders the facebook logo (a raster file) inside an SVG circle.

Result:

SVG模式应用于圆的结果

Source image:

源文件

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