Canvas Pocket Reference Scripted Graphics For HTML5 David Flanagan
Canvas Pocket Reference Scripted Graphics For HTML5 David Flanagan
com
https://ebookname.com/product/canvas-pocket-reference-
scripted-graphics-for-html5-david-flanagan/
OR CLICK HERE
DOWLOAD EBOOK
https://ebookname.com/product/jquery-pocket-reference-1st-
edition-david-flanagan/
https://ebookname.com/product/html5-pocket-reference-fifth-
edition-jennifer-niederst-robbins/
https://ebookname.com/product/html5-canvas-second-edition-steve-
fulton/
https://ebookname.com/product/the-greenhaven-encyclopedia-of-the-
renaissance-tom-streissguth/
U S Trade with Developing Countries Policy Programs and
Trends Policy Programs and Trends 1st Edition Kalan R.
Geisler
https://ebookname.com/product/u-s-trade-with-developing-
countries-policy-programs-and-trends-policy-programs-and-
trends-1st-edition-kalan-r-geisler/
https://ebookname.com/product/the-individualized-music-therapy-
assessment-profile-imtap-1st-edition-holly-tuesday-baxter/
https://ebookname.com/product/excellence-without-a-soul-does-
liberal-education-have-a-future-first-edition-lewis/
https://ebookname.com/product/neurology-board-review-an-
illustrated-study-guide-1st-edition-mowzoon-nima/
https://ebookname.com/product/the-decision-was-always-my-own-
ulysses-s-grant-and-the-vicksburg-campaign-1st-edition-timothy-b-
smith/
A Mother s Work How Feminism the Market and Policy
Shape Family Life 1st Edition Professor Neil Gilbert
https://ebookname.com/product/a-mother-s-work-how-feminism-the-
market-and-policy-shape-family-life-1st-edition-professor-neil-
gilbert/
Canvas
Pocket Reference
Canvas
Pocket Reference
David Flanagan
Printing History:
December 2010: First Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are
registered trademarks of O’Reilly Media, Inc. The Pocket Reference series
designation, Canvas Pocket Reference, the image of a gold weaver bird, and
related trade dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish
their products are claimed as trademarks. Where those designations appear
in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the
designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the
publisher and authors assume no responsibility for errors or omissions, or
for damages resulting from the use of the information contained herein.
ISBN: 978-1-449-39680-0
[TM]
1291908640
Contents
Preface vii
v
Index 97
vi | Table of Contents
Preface
vii
In general, you may use the examples in this book in your
programs and documentation. You do not need to contact
us for permission unless you’re reproducing a significant por-
tion of the code. We appreciate, but do not require, an attri-
bution like this: “From Canvas Pocket Reference by David
Flanagan (O’Reilly). Copyright 2011 David Flanagan,
978-1-449-39680-0.” If you feel your use of code examples falls
outside fair use or the permission given here, feel free to contact
us at [email protected].
To comment or ask technical questions about this book, send
email to:
Download from Wow! eBook <www.wowebook.com>
[email protected]
This book is also available from the Safari Books Online serv-
ice. For full digital access to this book and others on similar
topics from O’Reilly and other publishers, sign up at http://
my.safaribooksonline.com.
viii | Preface
CHAPTER 1
Canvas Tutorial
1
standardized by HTML5 but has been around for longer than
that. It was introduced by Apple in Safari 1.3, and has been
supported by Firefox since version 1.5 and Opera since version
9. It is also supported in all versions of Chrome. The
<canvas> tag is not supported by IE before IE 9, but can be
reasonably well emulated in IE 6, 7, and 8.
With those lines at the top of your web pages, <canvas> tags
and basic Canvas drawing commands will work in IE. Radial
gradients and clipping are not supported. Line width does not
scale correctly when the X and Y dimensions are scaled by dif-
ferent amounts, and you can expect to see other minor ren-
dering differences in IE as well.
3D Graphics in a Canvas
At the time of this writing, browser vendors are starting to im-
plement a 3D graphics API for the <canvas> tag. The API is
known as WebGL, and is a JavaScript binding to the OpenGL
standard API. To obtain a context object for 3D graphics, pass
the string “webgl” to the getContext() method of the canvas.
WebGL is a large, complicated, and low-level API that is not
documented in this book: web developers are more likely to
Download from Wow! eBook <www.wowebook.com>
Canvas Tutorial | 3
Figure 1-1. Simple canvas graphics
The Canvas API describes complex shapes as a “path” of lines
and curves that can be drawn or filled. A path is defined by a
series of method calls, such as the beginPath() and arc() in-
vocations in the preceding code. Once a path is defined, other
methods, such as fill(), operate on that path. Various prop-
erties of the context object, such as fillStyle, specify how
these operations are performed. The subsections that follow
explain:
• How to define paths, how to draw or “stroke” the outline
of a path, and how to fill the interior of a path
• How to set and query the graphics attributes of the canvas
context object, and how to save and restore the current
state of those attributes
• Canvas dimensions, the default canvas coordinate system,
and how to transform that coordinate system
• The various curve-drawing methods defined by the
Canvas API
• Some special-purpose utility methods for drawing
rectangles
• How to specify colors, work with transparency, and draw
with color gradients and repeating image patterns
• The attributes that control line width and the appearance
of line endpoints and vertices
• How to draw text in a <canvas>
We honked and snorted and sirened our way through the narrow,
dust-deep, crowded streets of Kalgan, as automobiles must in any
genuine Chinese city, now blocked completely by the deliberate foot-
going traffic, now by languid trains of ox-carts, and always quickly
surrounded by gaping and grinning Chinese, to whom a foreigner
seems always to remain a rare bird, however many of him may be
seen daily. Twice we were halted at ancient city gates by policemen
with fixed bayonets. They were somewhat more deferential to us, and
more easily satisfied with the credentials we chose to show, than
toward our two companions with their big red huchao, large as a
newspaper page, by means of which the local yamen had given them
permission for their journey. Russians are subject now to Chinese
law, and Americans are not, which at times makes a world of
difference. Yet it was at one of these same gates that an American
resident of Kalgan was killed by one of these same guards not long
afterward for refusing to submit to an illegal decree of the local
overlord.
For about two hours beyond the outer gate we climbed a stony
river-bed, wide enough to have carried a stream with ships on its
bosom, but merely crisscrossed by a narrow brook bringing down silt
from the treeless mountains above. The city abandoned us with
reluctance, struggling along for a way in closely crowded shops and
dwellings, then straggling more and more until it dwindled to a
single row of mud houses on either side, finally to little clusters of
huts strung together like loose strings of beads, and breaking up at
last into isolated hamlets dug back cave-like into the cliffs of dry
fantastic hills that rose yellow-brown above and beyond us. The
unpromising route was dense with traffic,—long trains of camels
haughtily treading past, strings of ox-carts with the solid, heavily
riveted wheels indigenous to China, patient-faced mules and donkeys
carefully picking their way through acres of tumbled stones, throngs
of cheery, unbelligerent Chinese in blue denims, mingled here and
there with a more hardy, weather-beaten, hard-faced Mongol, a stray
soldier perhaps, with an ancient gun slung over his sheepskin-clad
shoulder, or a robust lama in filthy quilted garments that had once
been red or yellow. Whenever some of the many obstacles brought us
momentarily to a halt these religious tramps came to beg the half-
smoked cigarette from between our lips, to feel the car all over, as if
it were some new breed of horse, and to hint that a dollar or a dime
or a few coppers or even some remnants of food would be more or
less gratefully accepted.
Where the waterless river tumbles down from the high plateau
across which lies nearly all the route to Urga, the slope is too swift
even for the sturdiest of motors, wherefore the adaptable Chinese
villagers have found a new source of income. Before this steeper
section was reached, Chinese along the way began to wave appeals at
us, to point out their lean and hungry mules and horses, in some
cases even to climb up over our baggage rampart with harnesses in
their hands, begging the job of hauling us to the top. Three horses, a
mule, and a donkey were at length engaged, after the bargaining
indispensable to both races concerned in the transaction, hitched
with long rope traces to the front axle of our now silent car, and for
more than an hour they toiled upward under the discouragement of
three shrieking Chinese drivers and their cracking whips, at a pace
which that one of us who chose to walk easily outdistanced.
From the chaos of broken rocks where the animals were allowed to
abandon us stretched a tumbled brown world not unlike the upper
reaches of the Andes. Of road in the Western sense there had been
none from the start; there was even less now. Across pell-mell
hillocks with rarely a yard of level space between them, among rocks
of every jagged and broken form, we plowed for the rest of the
morning. Cattle—curiously effeminate-looking cattle, with long
ungraceful horns—flocks of sheep and goats intermingled, files of
camels under varying cargo, here and there a cluster of black pigs
rooting more or less in vain, marked a trail that might otherwise
have been less easy to follow. Men in cotton-padded clothing and
sheepskins plodded beside their animals, or tramped alone with a
worn and faded roll of bed and belongings on their backs; cheery,
amused, seldom-washed people smiled at us over the mud walls of
their compounds; for some time big ruined towers of what was, or
was to have been, another Great Wall, stood at brief intervals along
the crest of the bare, yellow-brown ridge beside us. Then came
rolling stretches of grain, principally oats, most of it already
harvested by the sickle and carry-on-the-back method, for all the
vastness of the cultivation, and lying in carefully spaced bundles in
the fields where it fell, or set up in long rows of closely crowded
shocks near the hard-earth threshing floors.
Bit by bit even this cultivation grew rare and scattered, and finally
died out entirely. By the time the speedometer registered eighty
miles from Kalgan we were spinning along, often at thirty miles an
hour, across high, brown, grass-covered plains, still somewhat
uneven, but with little more than a suggestion of hilliness remaining.
Flocks of sheep far off on the sloping sides of the horizon looked like
patches of daisies; veritable gusts of gray-blue birds of stately flight,
suggestive both of cranes and of wild geese, rose in deliberate haste
before us and floated away to the rear in a vain effort to outdistance
us. Almost frequently we passed long camel caravans, broken up into
sections of a dozen animals each, tied together by a sort of wooden
marlinespike thrust through their noses beneath the nostrils and
attached by a cord to the pack of the animal ahead, the first of each
dozen led by a well padded, skin-wrapped man who was more often
Chinese than Mongol. Some of these camel-trains seemed endless,
with dozen after dozen of the leisurely, soft-footed animals slowly
turning their heads to gaze, with a disdainful curiosity that suggested
a world-weary professor looking out from beneath his spectacles at
incorrigible mankind, upon this strange and impatiently hasty rival
that sped breathlessly past them. Now and again a beast shuffled
sidewise away from us, uttering that absurd little falsetto squeak
which is the camel’s inadequate means of protest at a cruel world;
but most of them refused to be startled into undignified activity by
any such ridiculous apparition. Once on the journey I counted a
caravan bound for Urga which stretched from horizon to horizon
across the brown undulating world; and there were thirty dozen
camels bearing cargo, and a score of outriders to keep the expedition
in order.
We were glad, indeed, to see the sun again next morning, when at
last it burst up like the exhaust from a puddling furnace over the low,
level horizon. Already we had bumped our way back to the
“highway,” as worthy of the name as the caminos reales, the “royal
roads,” of South America are of theirs, and had sped some distance
along it. The eyes suffered most in this glaring light and the incessant
strong head wind from which nothing short of entirely wrapping up
the head could protect them. The constant bumping and tossing
made up for any lack of exercise. Among myriad rock-heaps, natural
and prayerful, we crossed the frontier between Inner and Outer
Mongolia, marked merely by two huger stone-heaps on either side of
the there sunken trail, the summits connected by a wire from which
hung tattered bits of cloth prayers and various mementos of the
pious, culminating in a weather-beaten straw hat of Chinese make.
That was all, except the immensity of the desert, for the frontier-
station was still about fifty miles distant. Then the rock-heaps died
out, and the earth as far as we could see it was thickly covered with
millions of little mounds, like untended Chinese graves, with hints of
scanty tuft-grass on top of them. At long intervals we passed a
caravan, the dull-toned notes of the bell-camels reaching our ears
momentarily as we dashed past. The first camel of one long train
carried the American flag at his masthead, so to speak, to warn
would-be marauders that the hides and wool behind him were under
whatever protection our consuls and diplomats in the former
Chinese Empire have to offer. Otherwise the world about us was
mainly a confirmation of the fact that, while China proper estimates
the density of her population at two hundred and twenty-five to the
square mile, Mongolia’s is rated at two.
Were the world not so slow to accept geographical changes, even in
these days of the constant remaking of maps, we should long since
have ceased to distinguish between Mongolia and China “proper.”
Though the Chinese Republic claims, and to a certain extent
maintains, the loyalty of that strip of earth bordering her on the
north and known as Inner Mongolia, the vast region we call Outer
Mongolia cast off Chinese rule a decade ago. More exactly, it never
was under Chinese rule, at least in modern times, for barely had their
kindred Manchus been driven from the throne of China than the
Mongols asserted their independence from the new-formed republic.
That was why we Americans had looked forward with some
misgiving to our arrival in Ude, which occurred early on this third
day. Ude consists of half a dozen yourts and a new mud-walled
telegraph station, a desolate spot, owing its location to a near-by
water-hole. But it is the place where the merits or demerits of
persons entering Outer Mongolia from China are passed upon—
passed upon by unpolished Mongols who have little knowledge of,
and less interest in, the way such things are handled at other
boundaries between the countries of the globe. The Russians had no
misgivings; while men of their race would not willingly have traveled
to Urga eighteen months before, they were now, as it were, among
their own people. But, for reasons which will in due time be
apparent, there is just now a certain lack of welcome in Mongolia
toward Americans, in which the British and certain other important
nationalities share. Less than a month before, two Englishmen in
their own car had been halted at Ude and refused admission to the
land beyond, eventually giving up lengthy and useless negotiations to
have this decision reversed, and returning to China. We had no
“papers” calling upon Mongolia to admit us. Our legation in Peking
had only been able to tell us that, if our passports were sent to the
Chinese foreign office, they would be returned—long afterward—with
the information that, while Mongolia was still Chinese territory, it
was in the hands of rebels—they might even have called them bandits
—and since the Chinese Republic could not guarantee the safety of
foreigners in that region, they could not consent to our traveling
there, even to the extent of giving us a visé. The Mongols themselves
have no accredited representative in China, naturally, and while
certain other agents in Peking might have smoothed things over for
us if they had wished, it is their policy to pretend that they and those
they represent have no real power in Mongolia, apparently in the
hope of keeping the world ignorant as long as possible of their doings
in that region. It is customary, therefore, for those citizens of
Western nations who wish to enter Outer Mongolia to pick up their
traps and go, regardless of legal permissions.
But all our misgivings of being turned back at Ude were worry
wasted. The Mongols have a reputation for instability in the conduct
of affairs of government, of stiff-necked severity at one moment and
great leniency in quite a similar matter the next; for after all they are
little more than adult children to whom government is a new and
amusing plaything. Moreover it may be that the letter and the bottle
of vodka which the chief of our party brought for the Ude functionary
had their effect; at any rate he not only did not demand our papers
but did not even ask to see us, so that by the time we had breakfasted
on our own food and local hot water in a yourt next to the official one
we were free to continue to Urga.
A cross the broken valley at a gallop came two mounted men who
turned out to be Mongol soldiers, picturesque certainly, but not
otherwise particularly inviting. As they rode, they waved their rifles
wildly in the air, and were apparently bellowing to us orders which
the raging wind carried away before the sounds reached us. When
they drew near, their uniforms proved to be the usual costume of the
lower-class Mongol—heavy red knee-boots, pagoda-like fur hats, and
a faded, quilted kind of bath-robe gown covering the rest of their
iniquities; but on their chests and backs were sewed two cloth
patches a foot square on which were several upright lines of Mongol
writing, announcing their official capacity. But for these we might
easily have mistaken them for bandits, for both their manner of
riding down upon us and their air toward us when they had arrived
suggested that they had captured booty and prisoners for ransom
rather than that they had merely come to escort us to town.
One of them, it appeared from their actions, must get into the car
with us; the other would have to ride in with the horses. Like
children who very rarely have the chance of an automobile-ride, they
quarreled and argued for a long time, while the biting wind snapped
and lashed at us, as to which was entitled to the privilege, meanwhile
flourishing their aged rifles with a carelessness that made even such
time-honored weapons dangerous. At length one of them won the
point and climbed unceremoniously aboard, mopping his muddy feet
on our robes, stretching himself out at ease partly on our knees,
partly on our most breakable baggage, and poking us, perhaps
unintentionally but none the less unpleasantly, in the ribs with the
business end of his loose-triggered rifle, while the loser sourly turned
away with the horses and the expression of a six-year-old who had
been deprived of his toys and driven from the playground.
We forded half a dozen stony little streams, for the going had
become abominable in ratio as we approached Urga; we were waved
hither and yon across the valley by other rifle-shaking, vainly
shouting soldiers, and finally brought up at an ordinary little round
felt hut with a smoking stovepipe protruding from its top. It must
have been much more comfortable inside this than out in the bitter
wind, for those within showed no haste in braving the outer
temperature. Finally, however, two or three Mongols crawled
through the low door and demanded our huchao, our Chinese permit
to make the journey. There was an interminable argument over this,
mainly inside the yourt, which we had not been invited to enter.
Then two more bullying soldiers with poorly controlled rifles
tumbled into the car and ordered us to drive on.
Before a yamen that might have been mistaken either for a run-
down temple or a well kept stable we were again halted and
commanded to dismount. This place, it turned out, was not yet Urga,
but the former Chinese merchant section of Mai-Mai-Ch’eng (“Buy-
Sell-Town”) some miles away from the sacred city, in which trading
was until recently forbidden. Here a veritable mob of soldiers and
petty officials poured out upon us, led by an exceedingly insolent
youth in a rich, silky, but much soiled light-blue gown topped off by a
kind of archbishop’s miter. He demanded our weapons. We dug
them and the bit of ammunition we carried out of our baggage,
protesting in vain that as this was all to be examined at the next
yamen, and armed guards were to conduct us there, this extra labor
of disentangling our overloaded car was unnecessary. But it was
plain that there were at least two motives for putting us to this
gratuitous trouble: the insolent Mongol youth did not wish to lose an
opportunity to show his authority to the full, particularly toward men
of a race which seldom fell into his hands; and the whole posse was
eager to meddle with our belongings as much as possible. They
passed our revolvers and my companion’s rifle from hand to hand,
each trying his own method of manipulating them. Fortunately—at
the time we felt it was unfortunate—we had not loaded them, or
several tragedies might have ensued before their curiosity was
satisfied and we were allowed to conclude our journey. Then the
overbearing youth in charge decided that he must search our persons
for weapons, though we had given our word that we carried none.
The implied insult would not have mattered so much had not his
hands looked as if he had been handling Gobi fuel incessantly from
childhood without a pause even to wipe them, and had his manner
been less that of the protected bully venting an unaccountable spleen
against the whole white race. But cleanliness and common courtesy,
we soon learned, are the two qualities most foreign to the crowd now
ruling Outer Mongolia.
The quarrel as to who should have the privilege of the automobile-
ride into Urga was at length decided in favor of all who could pile
themselves into and about the car and baggage. How the machine
escaped a broken back under the burden was a mystery which even
Detroit probably could not have explained. Then there came a delay
while the blue-gowned youth found and adjusted a fanciful pair of
goggles, in all likelihood filched from the baggage of some previous
victim, and without which of course the two- or three-mile ride
ahead would have been unendurable. We groaned away at last, rifles
and our own weapons covering us on every side, first through a half-
ruined town of mud alleys between endless palisades of upright logs
of the pine family, then across a stony, barren, wind-swept space
with several axle-cracking little streams to be forded. Between
bumps we caught glimpses of the several distinctly isolated sections
of Urga, its golden temples and black dogs, its one lofty building, and
the Tibetan texts in stone on the flank of its sacred mountain across
the valley. Then we were suddenly turned into a noisome back yard
peopled with shoddy-clad and unwashed soldiers and prisoners, the
latter engaged in worse than menial tasks under the bayonet-points
of the former; the gate to the outside world was closed and barred,
and a new set of examiners fell upon us.
If a gang of young East Side New York rowdies should suddenly get
the complete upper hand in the city, I can imagine them going
through the belongings of their victims along Fifth Avenue in quite
the same way as now befell our own. At a word from a superior who
would himself scarcely have inspired a lone lady with confidence on a
dark night, there sprang forward from all sides a dozen young men
who seemed to have been specially chosen for their gangster-like
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com