LEARNING JAVASCRIPT - Trang 33

4

If you want to learn more about CSS and HTML, I recommend the Codecademy’s free

HTML & CSS track

.

Drawing Graphics Primitive

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.

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 para‐

graph, for example):

<

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.

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 spar‐

ingly. 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.

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

;

}

Drawing Graphics Primitive | 9

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.