构造的SVG不适用于绘制HTML的地方

Constructed SVG does not work where HTML-drawn does

本文关键字:HTML 绘制 不适用 SVG 适用于      更新时间:2023-09-26

当我在HTML源代码中使用viewBox属性绘制SVG时,我可以重新调整窗口大小,并且我的SVG会自动缩放。

<svg xmlns="http://www.w3.org/2000/svg" viewBox="-350 -250 700 500">
    <circle r="200" class="face" fill="green"/>
    <path fill="none" class="face"
       transform="translate(-396,-230)" 
       d="M487.41, 282.411c-15.07, 36.137-50.735, 61.537-92.333,
          61.537 c-41.421, 0-76.961-25.185-92.142-61.076"/>
    <circle cx="-60" cy="-50" r="20" fill="black"/>
    <circle cx="60" cy="-50" r="20" fill="black"/>
</svg>

但是,当我用D3.js构建完全相同的SVG时,viewBox就不起作用了!

var smileyRed = d3.select("#js")
                .append("svg")
                .attr("xmlns", "http://www.w3.org/2000/svg")
                .attr("viewbox", "-350 -250 700 500");
smileyRed.append("circle")
     .attr('r','200')
     .attr('class','face')
     .attr('fill','red');
smileyRed.append("path")
    .attr('fill','none')
    .attr('class','face')
    .attr('transform','translate(-396,-230)')
    .attr('d','M487.41, 282.411c-15.07, 36.137-50.735, 61.537-92.333,
               61.537 c-41.421, 0-76.961-25.185-92.142-61.076');
smileyRed.append("circle")
     .attr('cx','-60')
     .attr('cy','-50')
     .attr('r','20')
     .attr('fill','black');
smileyRed.append("circle")
     .attr('cx','60')
     .attr('cy','-50')
     .attr('r','20')
     .attr('fill','black');

JSfiddle演示

viewBox是区分大小写的属性

viewBox 代替viewbox

.attr("viewBox", "-350 -250 700 500");

从这里:http://www.w3.org/TR/SVG/styling.html#CaseSensitivity

通过表示属性进行的属性声明用区分大小写的XML[XML10]表示。