简体   繁体   中英

How to use “g” with svg in coffee script to rotate object in d3 ?

I'm trying to create something similar to

    <svg width="12cm" height="4cm" viewBox="0 0 1200 400"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <desc>Example rect02 - rounded rectangles</desc>

  <!-- Show outline of canvas using 'rect' element -->

  <rect x="100" y="100" width="400" height="200" rx="50"
        fill="green" />

  <g transform="translate(700 210) rotate(-30)">
    <rect x="0" y="0" width="400" height="200" rx="50"
          fill="none" stroke="purple" stroke-width="30" />
  </g>
</svg>

to get similiar to this image below 在此输入图像描述

with this coffeescript below

canvas = d3.select("body")
    .append("svg")
    .attr("width",2600)
    .attr("height",2600)


rect1 = canvas.append("rect")
    .attr("width",400)
    .attr("height",200)
    .attr("x",100)
    .attr("y",100)
    .attr("rx",50)
    .attr("fill","green")


rect2 = canvas.append("rect")
    .attr("width",400)
    .attr("height",200)
    .attr("x",650)
    .attr("y",50)
    .attr("rx",50)
    .attr("fill","none")
    .attr("stroke-width",30)
    .attr("stroke","Indigo")
  .append("g")
    .attr("transform","translate(700 200) rotate(-30)")

But having issue with the rect2 "indigo" couldn't get it to rotate using "g" and got something like this instead.

在此输入图像描述

New to coffee and d3 , any recommendation would be appreciated.

Thanks.

You seem to insert the <g> element into the second rectangle and not vica versa. Thus the transformation on the <g> does not affect the rectangle at all. You need first to append the <g> to the canvas and then append the <rect> to that <g> :

// ...

rect2 = canvas.append("g")
    .attr("transform","translate(700 200) rotate(-30)")
  .append("rect")
    .attr("width",400)
    .attr("height",200)
    .attr("x",650)
    .attr("y",50)
    .attr("rx",50)
    .attr("fill","none")
    .attr("stroke-width",30)
    .attr("stroke","Indigo")

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