通过Raphael中的CSS控制矩形的填充

Controlling the fill of a rect through CSS in Raphael

本文关键字:填充 控制 Raphael 中的 CSS 通过      更新时间:2023-09-26

我正在使用Raphael,我想创建一个rect并通过CSS控制fill属性。

当我以经典的方式设置填充属性时,一切都很好:

    space = paper.rect(0,0,1000,500).attr({fill: "url('img/cell_background.png')"});

事实上,通过这种方法,我得到了正确的填充。如果检查元素,我可以看到在rect元素中指定了fill属性,它引用了svgdefs中定义的模式。

<svg>
   ...
   <defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); ">
        <pattern style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); " 
         id="E6992022-9B75-4D1E-9D44-6EC45CE420A1" x="0" y="0" 
         patternUnits="userSpaceOnUse" height="5" width="9" 
         patternTransform="matrix(1,0,0,1,0,0) translate(0,0)">
           <image style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); " 
                      x="0" y="0" 
                  href="img/cell_background.png" width="9" height="5">
               </image>
        
            </pattern>
      </defs>
      <rect style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); " 
        x="0" y="0" width="1000" height="500" r="0" rx="0" ry="0" 
    fill="url(#E6992022-9B75-4D1E-9D44-6EC45CE420A1)" stroke="#000" 
    class="space">
      </rect>
    ...
</svg>

如果我使用以下代码创建rect

space = paper.rect(0,0,1000,500);
space.node.setAttribute("class","space");

然后在.css中我定义:

.space {
fill: url('img/cell_background.png');
stroke: #ff0000;
}

然后,检查的html显示一个fill='none'作为rect属性,矩形正确地呈现为红色边框,但填充为实心黑色。

一些进一步的观察:

  1. js在js/文件夹中,css在css/文件夹中,image在img/文件夹中。我试过/img","/img和img,但我有相同的行为
  2. 如果我不放填充物,我会得到预期的白色填充物
  3. 如果我放置CCD_ 8,则获得白色背景
  4. 如果我放置fill: #ff0000,我得到期望的红色背景
  5. 如果我使用假文件名,我会获得相同的黑色背景
  6. 行为与Chrome和Firefox一致

从第四点和第五点来看,似乎找不到文件,但我认为已经用尽了我应该检查的路径组合(css使用'../img路径在同一文件夹中找到其他图像)。我想问题出在别的地方。

有人有类似的经历吗?

在SVG中,不能像处理HTML元素那样只为元素指定位图背景url。在SVG中执行此操作的标准方法是通过pattern定义。拉斐尔用一个简单的fill: url(...)从你身上抽象出这种混乱。

你可以用CSS样式表加载模式,比如。。。

.space {
  fill: url('img/cell_background.svg#bitmap');
  stroke: #ff0000;
}

当然,cell_background.svg#bitmap仍然需要看起来像。。。

<svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink">
   <defs>
        <pattern id="bitmap" x="0" y="0" patternUnits="userSpaceOnUse" height="5" width="9">
           <image x="0" y="0" xlink:href="img/cell_background.png" width="9" height="5">
           </image>
         </pattern>
    </defs>
</svg>

当然,这只会使事情变得更加复杂。

rect显示为黑色的原因是引擎试图加载一个缺失的填充定义(渐变或图案),该定义默认为黑色。