2011-09-28 46 views
15

我知道这不是导致此问题的jQuery SVG库,但是当在整数x,y坐标上呈现水平或垂直SVG行时,行宽为2px而不是1px。这可能与抗锯齿有关。为了使它们固定,并绘制一条宽度完全为1px的线条,我需要通过添加0.5px来调整坐标。使用jQuery绘制网格SVG生成2px行而不是1px

有没有办法让行1px厚而不必像这样调整它们?

回答

31

解决该问题的一个方法是一些CSS施加到行:

.thelines{ 
    shape-rendering:crispEdges 
} 

The spec chapter on shape-rendering property.

基本上它关闭抗锯齿的线,而不是直的线的水平或垂直可能看起来不漂亮。

但是,可能你最好坚持在行的坐标中加上.5,因为浏览器会按照他们的要求来做:线条在精确的坐标上,笔画在线条的两侧画出,半个像素这里和那里的半像素。

+0

这可以工作,如果我可以关闭AA,它将解决问题。 –

+0

好吧,这个工作,唯一的问题,如果你把它称为shapeRendering,就像他们在他们的文档中提到的那样,jQuery SVG样式不能正确设置,它必须是形状渲染,否则它不起作用。 –

+0

当你将它设置为一个DOM对象属性:'yourElement.style.shapeRendering =“crispEdges”'时,我想它必须是'shapeRendering',但是在一个style属性中它应该保留它的原始名称。 –

10

所以你想要一个像素宽的水平和垂直线显示清晰而不是模糊的边缘。

如果您的SVG 所有的坐标都是整数,也许你可以通过0.5抵消整个图像,通过使用变换的元素:

// first group has no transform 
// lines appear blurred, because they are centered on boundary of two pixels 
<g id = "blurred"> 
    <line x1="10" y1="10" x2="110" y2="10" stroke="black" stroke-width="1"/> 
    <line x1="10" y1="10" x2="10" y2="100" stroke="black" stroke-width="1"/> 
</g> 

    // second group has half pixel transform - 
    // lines will appear sharp because they are translated to a pixel centre 
    <g id="sharp" transform="translate(0.5,0.5)"> 
    <line x1="120" y1="10" x2="220" y2="10" stroke="black" stroke-width="1"/> 
    <line x1="120" y1="10" x2="120" y2="100" stroke="black" stroke-width="1"/> 
</g> 

svg renders like this

但这决不适用于未用整数坐标定义的水平/垂直线,或其他变换将它们从整数坐标移开的地方。

所以,如果这个想法不能用来解决你的问题,那么你可能需要一个'像素捕捉'技术。这将在绘制之前分析一条线。如果线是垂直或水平的(变换之后),那么您需要调整坐标,以便它们在变形之后最终在像素中心中。

您可能会感兴趣查看有关此常见问题的背景信息的WPF Pixel Snapping说明。

+0

这听起来像个好主意! :)谢谢 –

+0

setTimeout(function(){ d3.selectAll('.cpu-statistics.c3-ygrid-lines .c3-ygrid-line') .attr('transform',function(d,i){ return'translate(0.5,0.5)'; }); },300); – Ivan

0

只需使用填充1px宽的矩形(当然只适用于水平/垂直线)。

例如对于全宽水平线:

<rect x="0" y="0" width="100%" height="1" fill="#c2c2c2"></rect> 

每次完美的1px宽线。

相关问题