svgdotjs / svg.js

The lightweight library for manipulating and animating SVG
https://svgjs.dev
Other
11.01k stars 1.07k forks source link

.use() has different behavior than .clone().addTo() #1172

Closed michael-brade closed 3 years ago

michael-brade commented 3 years ago

Hi,

if I paste the following code

var draw = SVG().addTo('#canvas').size('100%', '100%')
draw.viewbox(0,0,30,30)

const disc1 = draw.rect(10, 1).dy(3)    // <<---- HERE

const cap = draw.rect(8,5)
                .translate(0, disc1.rbox(draw).y2)
                .fill("gray")
                .stroke({ width: 0 })

disc1.clone().addTo(draw)
     .y(cap.rbox(draw).y2)
     .fill("red")

draw.use(disc1)
    .y(cap.rbox(draw).y2)
    .fill("green")

in this fiddle, then you can see that the green rect is below the red rect, even though both have their y value set to the same value.

However, if I remove the .dy(3) in line 4 (marked with HERE), then the green rect ends up in the correct position.

This doesn't seem to be intentional ;-) Or am I wrong?

Fuzzyma commented 3 years ago

This is totally intended. You clone the element and set a new y-value in your first case. In your second case, you add a new y value to the use element. It means, you shadow copy the rectangle with its dy of 3 and then add another y of 9. If you give use a position it will move the copied element by that amount. The copied element is at y=3 and its moved by 9

michael-brade commented 3 years ago

Oh, darn. Thanks :-) So I cannot use an element and absolutely change the position? Fair enough, I'll just clone then :)