Drawing Graphics Primitive javascript tutorial 2019

0
6

Among many of the benefits HTML5 brought was a standardized graphics interface. The HTML5 canvas allows you to draw graphics primitives like squares, circles, and polygons. Using the canvas directly can be painful, so we’ll use a graphics library called Paper.js to take advantage of the HTML5 canvas.
Paper.js is not the only canvas graphics library available: KineticJS, Fabric.js, and EaselJS are very popular and robust alternatives. I’ve used all of these libraries, and they’re all very high quality.

javascript

Before we start using Paper.js to draw things, we’ll need an HTML canvas element to draw on. Add the following to the body (you can put it anywhere; after the intro paragraph, for example):

Also read :How to prevent Google and other apps from tracking your location

<canvas id=”mainCanvas”></canvas> Note that we’ve given the canvas an id attribute: that’s how we will be able to easily refer to it from within JavaScript and CSS. If we load our page right now, we won’t see anything different; not only haven’t we drawn anything on the canvas, but it’s a white canvas on a white page and has no width and height, making it very hard to see indeed.

Also read :How to Connect a Smartphone to Car Bluetooth

Every HTML element can have an ID, and for the HTML to be valid (correctly formed), each ID must be unique. So now that we’ve created a canvas with the id “mainCanvas”, we can’t reuse that ID. Because of this, it’s recommended that you use IDs sparingly. We’re using one here because it’s often easier for beginners to deal with one thing at a time, and by definition, an ID can only refer to one thing on a page.

Also read :Use these five easy ways to increase Wifi speed

Let’s modify main.css so our canvas stands out on the page. If you’re not familiar with CSS, that’s OK—this CSS is simply setting a width and height for our HTML element, and giving it a black border:4
#mainCanvas { width: 400px; height: 400px; border: solid 1px black;

If you reload your page, you should see the canvas now. Now that we have something to draw on, we’ll link in Paper.js to help us with the drawing. Right after we link in jQuery, but before we link in our own main.js, add the following line:

<script src=“https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.9.24/ ↩ paper-full.min.js”></script>

Note that, as with jQuery, we’re using a CDN to include Paper.js in our project You might be starting to realize that the order in which we link things in is very important. We’re going to use both jQuery and Paper.js in our own main.js, so we have to link in both of those first. Neither of them depends on the other, so it doesn’t matter which one comes first, but I always include jQuery first as a matter of habit, as so many things in web development depend on it.
Now that we have Paper.js linked in, we have to do a little work to configure Paper.js. Whenever you encounter code like this—repetitive code that is required before you do something—it’s often called boilerplate. Add the following to main.js, right after ‘use strict’ (you can remove the console.log if you wish):

paper.install(window); paper.setup(document.getElementById(‘mainCanvas’));
// TODO

paper.view.draw(); The first line installs Paper.js in the global scope (which will make more sense in Chapter 7). The second line attaches Paper.js to the canvas, and prepares Paper.js for drawing. In the middle, where we put TODO is where we’ll actually be doing the interesting stuff. The last line tells Paper.js to actually draw something to the screen. Now that all of the boilerplate is out of the way, let’s draw something! We’ll start with a green circle in the middle of the canvas. Replace the “TODO” comment with the following lines:

Recomended For You :

var c = Shape.Circle(200, 200, 50); c.fillColor = ‘green‘;

Refresh your browser, and behold, a green circle. You’ve written your first real JavaScript. There’s actually a lot going on in those two lines, but for now, it’s only important to know a few things. The first line creates a circle object, and it does so with three arguments: the x and y coordinates of the center of the circle, and the radius of the circle. Recall we made our canvas 400 pixels wide and 400 pixels tall, so the center of the canvas lies at (200, 200). And a radius of 50 makes a circle that’s an eighth of the width and height of the canvas. The second line sets the fill color, which is distinct from the outline color (called the stroke in Paper.js parlance). Feel free to experiment with changing those arguments

2.   Automating Repetitive Tasks 

Consider what you’d have to do if you wanted not just to add one circle, but to fill the canvas with them, laid out in a grid. If you space the circles 50 pixels apart and make them slightly smaller, you could fit 64 of them on the canvas. Certainly you could copy the code you’ve already written 63 times, and by hand, modify all of the coordinates so that they’re spaced out in a grid. Sounds like a lot of work, doesn’t it? Fortunately, this kind of repetitive task is what computers excel at. Let’s see how we can draw out 64 circles, evenly spaced. We’ll replace our code that draws a single circle with the following

var c; for(var x=25; x<400; x+=50) { for(var y=25; y<400; y+=50)

{ c = Shape.Circle(x, y, 20); c.fillColor = ‘green’; } }

If you refresh your browser, you’ll see we have 64 green circles! If you’re new to programming, what you’ve just written may seem confusing, but you can see it’s better than writing the 128 lines it would take to do this by hand. What we’ve used is called a for loop, which is part of the control flow syntax that we’ll learn about in detail in Chapter 4. A for loop allows you to specify an initial condition (25), an ending condition (less than 400), and an increment value (50). We use one loop inside the other to accomplish this for both the x-axis and y-axis.

There are many ways we could have written this example. The way we’ve written it, we’ve made the x and y coordinates the important pieces of information: we explicitly specify where the circles will start and how far apart they’ll be spaced. We could have approached this problem from another direction: we could have said what’s important is the number of circles we want (64), and let the program figure out how to space them so that they fit on the canvas. The reason we went with this solution is that it better matches what we would have done if we had cut and pasted our circle code 64 times and figured out the spacing ourselves.

3.      Handling User Input

So far, what we’ve been doing hasn’t had any input from the user. The user can click on the circles, but it doesn’t do anything. Likewise, trying to drag a circle would have no effect. Let’s make this a little more interactive, by allowing the user to choose where the circles get drawn. It’s important to become comfortable with the asynchronous nature of user input. An asynchronous event is an event whose timing you don’t have any control over. A user’s mouse click is an example of an asynchronous event: you can’t be inside your users’ minds, knowing when they’re going to click. Certainly you can prompt their click response, but it is up to them when—and if—they actually click. Asynchronous events arising from user input make intuitive sense, but we will cover much less intuitive asynchronous events in later chapters. Paper.js uses an object called a tool to handle user input. If that choice of names seems unintuitive to you, you are in good company: I agree, and don’t know why the Paper.js developers used that terminology.5 It might help you to translate “tool” to “user input tool” in your mind. Let’s replace our code that drew a grid of circles with the following code:

var tool = new Tool();
tool.onMouseDown = function(event) { var c = Shape.Circle

(event.point.x, event.point.y, 20); c.fillColor = ‘green’; };

The first step in this code is to create our tool object. Once we’ve done that, we can attach an event handler to it. In this case, the event handler is called onMouseDown. Whenever the user clicks the mouse, the function we’ve attached to this handler is invoked. This is a very important point to understand. In our previous code, the code ran right away: we refreshed the browser, and the green circles appeared automatically. That is not happening here: if it were, it would draw a single green circle somewhere on the screen. Instead, the code contained between the curly braces after function is executed only when the user clicks the mouse on the canvas. The event handler is doing two things for you: it is executing your code when the mouse is clicked, and it is telling you where the mouse was clicked. That location is stored in a property of the argument, event.point, which has two properties, x and y, indicating where the mouse was clicked.

Note that we could save ourselves a little typing by passing the point directly to the circle (instead of passing the x and y coordinates separately):

var c = Shape.Circle(event.point, 20);

4. Hello, World 

Let’s conclude this chapter with a manifestation of Brian Kernighan’s 1972 example. We’ve already done all the heavy lifting: all that remains is to add the text. Before your onMouseDown handler, add the following:

var c = Shape.Circle(200, 200, 80);

c.fillColor = ‘black’; var text = new PointText(200, 200);

text.justification = ‘center’; text.fillColor = ‘white’;

text.fontSize = 20; text.content = ‘hello world’;

This addition is fairly straightforward: we create another circle, which will be a backdrop for our text, and then we actually create the text object (PointText). We specify where to draw it (the center of the screen) and some additional properties (justification, color, and size). Lastly, we specify the actual text contents (“hello world”). Note that this is not the first time we emitted text with JavaScript: we did that first with console.log earlier in this chapter. We certainly could have changed that text to “hello world.” In many ways, that would be more analogous to the experience you would have had in 1972, but the point of the example is not the text or how it’s rendered: the point is that you’re creating something autonomous, which has observable effects. By refreshing your browser with this code, you are participating in a venerable tradition of “Hello, World” examples. If this is your first “Hello, World,” let me welcome you to the club. If it is not, I hope that this example has given you some insight into JavaScript.

Most Popular Post :

LEAVE A REPLY

Please enter your comment!
Please enter your name here