Tải bản đầy đủ (.pdf) (10 trang)

Tài liệu Lập trình iphone chuyên nghiệp part 10 doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (477.37 KB, 10 trang )

Advanced Programming
Topics: Canvas and Video


The unique platform capabilities of iPhone and iPod touch enable developers to create innovative
applications inside of Mobile Safari that go beyond the normal “Web app” fare. Mobile Safari’s
support for the
canvas
element opens drawing and animation capabilities in an ordinary HTML
page that was previously available only by using Flash or Java. What’s more, deep inside the heart
of these two Apple devices lies the best portable audio and video media player that money can
buy. As an application developer, you can take advantage of these iPod capabilities by seamlessly
integrating multimedia into your mobile applications.
However, once you begin to open up these capabilities of Mobile Safari or the device itself, you
need to be sure that you are working with an iPhone and iPod touch rather than a desktop
browser. So, I’ll start by showing you how to identify the user agent for iPhone and iPod touch.
Identifying the User Agent
for iPhone and iPod touch
When you are trying to identify the capabilities of the browser requesting your Web site or
application, you generally want to avoid detecting the user agent and use object detection instead.
However, if you are developing an application designed exclusively for iPhone/iPod touch or
need Safari-specific features, such as
canvas
, then user agent detection is a valid option. Therefore,
this chapter assumes you are creating a Mobile Safari–specific application. Chapter 8 discusses
using media queries in general Web contexts.
c06.indd 121c06.indd 121 12/7/07 2:48:20 PM12/7/07 2:48:20 PM
Chapter 6: Advanced Programming Topics: Canvas and Video
122
The Mobile Safari user agent string for iPhone closely resembles the user agent for Safari on other
platforms. However, it contains an iPhone platform name and the mobile version number. Depending on


the version of Mobile Safari, it will look something like this:
Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko)
Version/3.0 Mobile/1A543a Safari/419.3
Here’s a breakdown of the various components of the user agent:

The platform string:
(iPhone; U; CPU like Mac OS X; en)
. Notice the “
like Mac OS X

line, which reveals some the underpinnings of the iPhone.

The WebKit engine build number:
AppleWebKit/420+
. This Safari version number is provided
on all platforms (including Mac and Windows).

The marketing version: (
Version/3.0
). This Safari version number is provided on all platforms
(including Mac and Windows).

OS X build number:
Mobile/1A543a
.

Safari build number:
Safari/419.3
.
The iPod touch user agent is similar, but distinct with

iPod
as the platform:
Mozila/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Geckto)
Version/3.0 Mobile/3A101a Safari/419.3
The version numbers will change, obviously, when Apple updates Mobile Safari, but the string structure
stays the same.
To test to whether the device is an iPhone/iPod touch or not, you need to perform a string search on

iPhone
and
iPod
. The following function returns
true
if the user agent is either an iPhone or iPod touch:
function isAppleMobile() {
result ((navigator.platform.indexOf(“iPhone”) != -1) ||
(navigator.userAgent.indexOf(‘iPod’) != -1))
}
Be sure not to test for the string
Mobile
within the user agent, because a non-Apple mobile device (such
as Nokia) might be based on the WebKit-based browser.
If you need to do anything beyond basic user agent detection and test for specific devices or browser versions,
however, consider using WebKit’s own user agent detection script available for download at
trac.webkit
.org/projects/webkit/wiki/DetectingWebKit
. By linking WebKitDetect.js to your page, you can test
for specific devices (iPhone and iPod touch) as well as software versions. Here’s a sample detection script:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“ /><html xmlns=” /><head>

<title>User Agent Detection via WebKit Script</title>
<meta name=”viewport” content=”width=320; initial-scale=1.0; maximum-scale=1.0;
user-scalable=0;”>
<script type=”application/x-javascript” src=”WebKitDetect.js”></script>
</head>
c06.indd 122c06.indd 122 12/7/07 2:48:20 PM12/7/07 2:48:20 PM
Chapter 6: Advanced Programming Topics: Canvas and Video
123
<body>
<p id=”log”></p>
</body>
<script type=”application/x-javascript”>
function addTextNode(str) {
var t = document.createTextNode(str);
var p = document.getElementById(“log”);
p.appendChild(t);
}
if ( WebKitDetect.isMobile() ) {
var device = WebKitDetect.mobileDevice();
// String found in Settings/General/About/Version
var minSupport = WebKitDetect.mobileVersionIsAtLeast(“1C28”);
switch( device ) {
case ‘iPhone’ :
if ( minSupport ) {
addTextNode(‘If this were a real app, I launch its URL right now.’);
break;
}
else {
addTextNode(‘Please upgrade your iPhone to the latest update before
running this application.’);

break;
}
case ‘iPod’ :
addTextNode(‘If this were a real app, I would launch its iPod touch
version.’);
default :
addTextNode( ‘This mobile device is not supported by this application.
Go to your nearest Apple store and get an iPhone.’);
}
}
else {
addTextNode( ‘Desktop computers are so 1990s. Go to your nearest Apple store and
get an iPhone.’ );
}
</script>
</html>
With the WebKitDetect.js script included, the
WebKitDetect
object is accessible. Begin by calling its

isMobile()
method to determine whether the device is or is not a mobile device. Next, check to ensure
that the mobile version is the latest release and save that result in the
minSupport
variable. The
switch

statement then evaluates the mobile devices. If it is an iPhone, then it checks to see if
minSupport
is true. If

so, then a real application would begin here. If
minSupport
is false, then the user is notified to update his
or her iPhone to the latest software version. The remaining two
case
statements evaluate for an iPhone or
else an unknown mobile device. The final
else
statement is called if the device is not a mobile computer.
Programming the iPhone Canvas
C++ and other traditional software programmers have long worked with a canvas on which they could
draw graphics. In contrast, Web developers typically program the presentation layer using HTML and
CSS. But unless they used Flash or Java, they had no real way to actually draw graphical content on a
c06.indd 123c06.indd 123 12/7/07 2:48:21 PM12/7/07 2:48:21 PM
Chapter 6: Advanced Programming Topics: Canvas and Video
124
Web page. However, both desktop and mobile versions of Safari support the
canvas
element to provide
a resolution-dependent bitmap region for drawing arbitrary content. The
canvas
element defines a
drawing region on your Web page that you then draw on using a corresponding JavaScript
canvas

object. The
canvas
element is part of the Web Hypertext Application Technology Working Group
(WHATWG) specification for HTML 5.0.
The canvas frees you up as an application developer to not only draw anything you want to, but also to

use canvas as a way to render graphs, program games, or add special effects. On Mac OS X, the canvas is
often used for creating Dashboard widgets. On iPhone, Apple makes use of the canvas for both the Clock
and Stocks built-in applications.
Canvas programming can be a mindset difference for Web developers used to manipulating existing
graphics rather than creating them from scratch. It is the loose equivalent of a Photoshop expert
beginning to create content using an Adobe Illustrator–like program in which all of the graphics are
created in a nonvisual manner.
Defining the Canvas Element
The canvas is defined using the
canvas
element:
<canvas id=”theCanvas” width=”300” height=”300”/>
Except for the
src
and
alt
attributes, the
canvas
element supports all of the same attributes as the
img

tag. However, the
id
,
width
, and
height
attributes are not required, but should be defined as a sound
programming practice. The
width

and
height
are usually defined in pixels, although it could also be a
percentage of the viewport.
You can place multiple
canvas
elements on a page, just as long as each one has its own unique id.
Getting a Context
Once a canvas region is defined on your Web page, you can then draw inside of the flat two-dimensional
surface using JavaScript. Just like a Web page, the canvas has an origin (0,0) in the top left corner. By
default, all of the x,y coordinates you specify are relative to this position.
As the first step in working with the canvas, you first need to get a
2d context
object. This object,
which is responsible for managing the canvas’ graphics state, is obtained by calling the
getContext()

method of the
canvas
object:
var canvas = document.GetElementById(“theCanvas”);
var context = canvas.getContext(“2d”);
Or, because you don’t normally work directly with the
canvas
object, you can also combine the
two lines:
var context = document.GetElementById(“theCanvas”).getContext(“2d”);
All of the drawing properties and methods you work with are called from the
context
object. The


context
object has many properties (see Table 6-1 ) that determine how the drawing looks on the page.
c06.indd 124c06.indd 124 12/7/07 2:48:21 PM12/7/07 2:48:21 PM
Chapter 6: Advanced Programming Topics: Canvas and Video
125
Table 6-1: Context Properties
Property Description
fillStyle
Provides CSS color or style (gradient, pattern) of the fill of a
path.
globalAlpha
Specifies the level of transparency of content drawn on the
canvas. Floating point value is between 0.0 (fully
transparent) and 1.0 (fully opaque).
globalCompositeOperation
Specifies the compositing mode to determine how the
canvas is displayed relative to background content.
Values include
copy
,
darker
,
destination-atop
,
destination-in
,
destination-out
,
destination-over

,
lighten
,
source-atop
,
source-in
,
source-out
,
source-over
,
xor
.
lineCap
Defines the end style of a line. String values include
butt

for flat edge,
round
for rounded edge,
square
for square
ends. (Defaults to
butt
.)
lineJoin
Specifies the way lines are joined together. String values
include
round
,

bevel
,
miter
. (Defaults to
miter
.)
lineWidth
Specifies the line width. Floating point value is greater than 0.
miterLimit
Specifies the
miter
limit for drawing a juncture between
line segments.
shadowBlur
Defines the width that a shadow covers.
shadowColor
Provides CSS color for the shadow.
shadowOffsetX
Specifies the horizontal distance of the shadow from the
source.
shadowOffsetY
Specifies the vertical distance of the shadow from the source.
strokeStyle
Defines the CSS color or style (gradient, pattern) when
stroking paths.
Drawing a Simple Rectangle
There are several techniques for drawing on the canvas. Perhaps the most straightforward is by drawing
a rectangle. To do so, you work with three context methods:



context.fillRect(x,y,w,h)
draws a filled rectangle.


context.strokeRect(x,y,w,h)
draws a rectangular outline.


context.clearRect(x,y,w,h)
clears the specified rectangle and makes it transparent.
c06.indd 125c06.indd 125 12/7/07 2:48:21 PM12/7/07 2:48:21 PM

×