Step 3: Draw canvas

The third step: drawing our canvas. We create our wrapper & bounds, then shift them to respect our margins.

Project Source Code

Get the project source code below, and follow along with the lesson material.

Download Project Source Code

To set up the project on your local machine, please follow the directions provided in the README.md file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.

This lesson preview is part of the Fullstack D3 Masterclass course and can be unlocked immediately with a single-time purchase. Already have access to this course? Log in here.

This video is available to students only
Unlock This Course

Get unlimited access to Fullstack D3 Masterclass with a single-time purchase.

Thumbnail for the \newline course Fullstack D3 Masterclass
  • [00:00 - 00:08] So our next step drawing the canvas is going to look a lot like the last lesson . So let's figure out what element we're hooking into that already exists on the page.

    [00:09 - 00:27] So in the page renders it's going to have this div with an idea of wrapper. Same as last time. So first let's create our wrapper element by using D3 select to grab that wrapper element.

    [00:28 - 00:44] So the hash again is because it has an ID of wrapper. And then let's add an SVG element and have it be respect our dimensions both the width and the height.

    [00:45 - 01:02] So the width is going to be dimensions dot width and the same thing for that height. Let's quickly just give it a border just to make sure it's in the right place.

    [01:03 - 01:16] So style border and pixel cell. Now we can see that we do have a square SVG element right here, which is great.

    [01:17 - 01:25] So next we'll want to create the bounds or other container element. So that's going to be on the wrapper.

    [01:26 - 01:44] We're going to want to create this group element. And then again, we're going to want to check if we're using an attribute or a CSS style for this one.

    [01:45 - 02:05] So let's go ahead and use a style and transform and then translate it and we're using this ES6 template string again. So we're going to want dimensions dot we're going to move it over by the left margin.

    [02:06 - 02:18] And then we want pixels and then we're also going to move it down dimensions dot margin dot top. And that's also in pixels.

    [02:19 - 02:32] Now you could also do this with an attribute. So the difference again between ATTR and style is that ATR creates an attribute on the element.

    [02:33 - 02:45] And the style creates a CSS style that targets that element. And one of the differences is that with ATTR you don't have to specify pixels.

    [02:46 - 02:51] In fact, it won't take any units. Otherwise it won't work.

    [02:52 - 02:58] But it's really up to you whether you want to do a CSS style or an SVG attribute on that.