Introduction to D3.js

Translate & Scale

Shirley Wu

Shirley Wu

Data Sketches
Introduction to D3.js

Check out a free preview of the full Introduction to D3.js course

The "Translate & Scale" Lesson is part of the full, Introduction to D3.js course featured in this preview video. Here's what you'd learn in this lesson:

Shirley explains that it is best practice to first translate the element and then scale afterwards, and adds that the order in which translate and scale are used within transforms is important. The order of the coordinates is important when using scales, because it determines where an element is placed.

Preview
Close

Transcript from the "Translate & Scale" Lesson

[00:00:00]
>> So we're going to this last little bit and scale. And so just like with translate, scale will also affect the whole coordinate system. And so if you scale, one thing that we might expect is for this to get bigger. But actually, the other thing is that the x and y positions will now be different also, because now maybe you can see but if we scale it by 2 in our unscaled coordinate system 200 is here but in our scaled coordinate system 200 is here.

[00:00:47]
So even if we're placing the squares, we're setting those same x and y on the squares. They will be positioned at different places. You might have noticed that in our exercise in this kind of rendering function, in the transform change the translate and the scale to be able to get this effect positioning and then sizing.

[00:01:15]
But it's extremely important the order in which we do this because depending on the order, the coordinate system will be different and thus like our flower petal and in this case the square will end up at different places. So for example, and I have these two, the blue one has a translate first and the purple one has a scale second.

[00:01:44]
And if we kinda take a look at scale and then let's say we translate by, so even the translate by, you can see is kind of the coordinate system is being shifted over almost like a different rate. And especially if you position now, if you position the the x and y it's going to be at completely different places.

[00:02:11]
And so that's just because, for example, for the second one, we're first scaling up. What's happening is that we're first scaling up our coordinate system. And so the translation is going to be within that kind of scaled up coordinate system, and that's why it's going to be different from if we had done it the other way around.

[00:02:38]
So, what I usually do and what I usually just keep in mind, because I've also had many bugs due to this kind of like ordering, is I always just default to translating first. Translate first, then scale.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now