javascript 用图案填充矩形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17776641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:35:01  来源:igfitidea点击:

Fill rect with pattern

javascriptcsssvgd3.js

提问by Amit Rana

I am using d3.js for graph. at some point i have to show data with some special part of graph for example if the values is cross some boundary then show that part with filling pattern. for more clear is there in and image.

我正在使用 d3.js 来绘制图表。在某些时候,我必须用图形的某些特殊部分显示数据,例如,如果值跨越某个边界,则显示该部分具有填充图案。更清楚的是有在和图像。

i get the rect part that cross the boundary but how can i fill it with this pattern? any css or canvas tricks?

我得到了跨越边界的矩形部分,但如何用这种模式填充它?任何 css 或 canvas 技巧?

enter image description here

在此处输入图片说明

Note : this image is just an example not the real one

注意:这张图片只是一个例子,不是真实的

回答by Brandon Boone

How about this:

这个怎么样:

Live Demo

Live Demo

JS

JS

var svg = d3.select("body").append("svg");

svg
  .append('defs')
  .append('pattern')
    .attr('id', 'diagonalHatch')
    .attr('patternUnits', 'userSpaceOnUse')
    .attr('width', 4)
    .attr('height', 4)
  .append('path')
    .attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2')
    .attr('stroke', '#000000')
    .attr('stroke-width', 1);

svg.append("rect")
      .attr("x", 0)
      .attr("width", 100)
      .attr("height", 100)
      .style("fill", 'yellow');

svg.append("rect")
    .attr("x", 0)
    .attr("width", 100)
    .attr("height", 100)
    .attr('fill', 'url(#diagonalHatch)');

Results

结果

enter image description here

在此处输入图片说明

回答by Kevin Lynch

To change the color would be simple, just a conditional ifstatement. Here's an example i've used before:

改变颜色很简单,只是一个条件if语句。这是我以前使用过的一个例子:

svg.selectAll("dot")    
        .data(data)                                     
    .enter().append("circle")                               
        .attr("r", 3.5)     
        .style("fill", function(d) {            // <== Add these
            if (d.close >= 50) {return "red"}  // <== Add these
            else    { return "black" }          // <== Add these
        ;})                                     // <== Add these
        .attr("cx", function(d) { return x(d.date); })       
        .attr("cy", function(d) { return y(d.close); });    

To add a pattern would be a little more involved as you first have to add the defs element to your SVG and then add your pattern to it

添加模式会更复杂一些,因为您首先必须将 defs 元素添加到您的 SVG 中,然后再将您的模式添加到其中

//first create you SVG or select it
var svg = d3.select("#container").append("svg");

//then append the defs and the pattern
svg.append("defs").append("pattern")
    .attr("width", 5)
    .attr("height", 5);