Safari Reference Library Apple Developer
Search

Safari Graphics, Media, and Visual Effects Coding How-To's

Graphics

How do I use the canvas tag to draw vector graphics and animation?

You can use the HTML5 <canvas> tag to set up a 2D bitmap context and then draw to that context using JavaScript. Graphics that can be drawn to the context of the <canvas> tag include lines, arcs, bezier curves, quadratic curves, images, shadows, and gradients. Many of the graphics that you see in Dashboard widgets on Mac OS X - such as the graph in the Stocks widget, and the hands of the World Clock widget - are drawn using the <canvas> tag. Listing 1 shows how to draw a circle using the <canvas> tag.

Listing 1: Draw a circle using the canvas tag.

<html>
<head>
<script>
function drawCircle() {

      /* get the main canvas and its context */
      var myCanvas = document.getElementById("myCanvas");
      var context = myCanvas.getContext("2d");

      /* draw a circle */
      radius = 90; x = 150; y = 150;
      context.beginPath();
      context.arc(x, y, radius, 0, 2 * Math.PI, false);
      context.closePath();
      context.setFillColor("3300FF");
      context.fill();
}
</script>
</head>
<body onload="drawCircle()">
      <canvas id="myCanvas" height="300" width="300" style="border: 2px solid; margin: 30px;" />
</body>
</html>

For more information about how to use the <canvas> tag, see the "Using the Canvas" section of WebKit DOM Programming Topics. For a list of available methods that you can use to draw vector graphics using <canvas>, see the "CanvasRenderingContext2D" class entry of the WebKit DOM Reference.



Media

How do I play audio or video in a webpage ?

Safari 3.1 and later supports HTML5 <audio> and <video> elements for embedding audio and video content in webpages. Using these elements, adding audio or video to a webpage is practically as simple as adding an image. Listing 2 shows an example of how to embed video in a webpage using a <video> tag. Since the autoplay attribute has been added, this video will automatically play once the webpage is loaded and the video is ready.

Listing 2: Using the video tag to embed video.

 <video src=sample.mov autoplay></video>

For more information on the <audio> and <video> elements, see the Safari HTML Reference and the "HTMLVideoElement", "HTMLAudioElement", and "HTMLMediaElement" class entries in the WebKit DOM Reference. For an example of how to define fallback content for browsers that do not support these elements, see the HTML Video Example sample code.

How do I add playback controls to audio and video content?

If you are using HTML5 <audio> and <video> elements to embed media in webpages, there are two ways to add playback controls. The first is to add the controls attribute to the element to indicate that default playback controls should be displayed - default controls will appear on the bottom edge of the embedded media. Listing 3 illustrates this technique.

Listing 3: Using the controls attribute.

 <video src=sample.mov controls ></video>

The second way to add playback controls is to use HTML and CSS to define custom controls in your interface, then use the scripting API that accompanies HTML5 <audio> and <video> elements to control playback through JavaScript. For instance, in the HTML Video With CSS Effects sample code, play, pause, seek forward and seek backward are invoked when the user clicks the appropriate button on an image of an iPod nano.

See the "HTMLMediaElement" class entry in the WebKit DOM Reference for a list of functions and attributes that you can use to control media playback.

How do I control volume and media playback?

The HTML5 <video> and <audio> elements supported in Safari 3.1 and later provide a rich scripting API for controlling and querying media playback. Among the functionality included in this API is the ability to play, pause, seek, and control volume. You can also query whether the media is paused, muted, ready to be played, buffered, and more.

Listing 4 shows how to create a button that gives the user basic playback control to play or pause the first video on a webpage.

Listing 4: Basic play/pause button.

<script>

function playPause() {

    var myVideo = document.getElementsByTagName('video')[0];

      if (myVideo.paused)
        myVideo.play();
    else
        myVideo.pause();
}

</script>

<input type=button onclick="playPause()" value="Play/Pause">

For more information on the functions and attributes for controlling and querying media playback, see the Safari HTML Reference, the "HTMLVideoElement", "HTMLAudioElement", and "HTMLMediaElement" class entries in the WebKit DOM Reference, and the HTML Video With CSS Effects sample code.



Visual Effects

How do I use CSS to position or transform webpage elements in 2D space?

CSS transform properties provide powerful formatting possibilities, without having to resort to plug-ins or static images to display the desired layout. HTML elements including text, images, media elements for audio and video, and more can be transformed via translation, scaling, rotation, skewing, or an affine transform matrix. Transforms are specified with the transform property, which supports a list of functions so that transforms can be chained together.

For example, to scale an image to half its size, flip it on the x-axis, and rotate it by 12 and a half degrees, you could use the CSS transform property in Listing 5.

Listing 5: CSS transform example.

<img src="safari.png" style="-webkit-transform: scale(0.5) scaleX(-1) rotate(12.5deg);"/>

This is just a glimpse of what is possible when using CSS transforms. More information about how to transform page elements using CSS can be found in the “Transforms” section of the Safari Visual Effects Guide.

How do I change the origin of a CSS transform?

When an element is translated, rotated, scaled, skewed or transformed in some other way using CSS, the origin of the transform defaults to the center of the element. You may find the need to transform an object with the origin positioned elsewhere on the element. You can specify the origin for a CSS transform using the transform-origin property. This property has the same syntax as background-position, and values for this property may be expressed using constants (top, bottom, left, right, center), as a CSS length unit, or as a percentage of the element size. Listing 6 illustrates how to set the transform origin to the top left corner when rotating a line of text.

Listing 6: Changing the origin of a CSS transform.

<div style="-webkit-transform:rotate(20deg); -webkit-transform-origin: top left;">
    Hello Safari Developers!
</div>

For more information on changing the origin of a transform, see the "Changing the Origin" section of the Safari Visual Effects Guide, and the Safari CSS Reference.

How do I use CSS transitions to add animation to my web content?

A transition can be thought of a type of simple animation. You specify which CSS properties will be transitioned, and the duration of the transition. When you use JavaScript or CSS to change the value of a CSS property, WebKit—the layout engine that powers Safari—takes care of smoothly animating from the old value to the new value.

For example, Listing 7 shows how to make a green box shrink to half its size and turn yellow when clicked, over a period of 1.5 seconds.

Listing 7: Using CSS transitions to add animation.

<html>
<head>
<style>
    #box {
        -webkit-transform: scale(1.0);
        -webkit-transition-property: -webkit-transform, background-color;
        -webkit-transition-duration: 1.5s;
        background-color: green;
        border: 2px solid;
        height: 200px;
        width: 200px;
        }
</style>
<script>
    function transitionBox(box) {
        box.style.webkitTransform = 'scale(0.5)';
        box.style.backgroundColor = 'yellow';
    }
</script>
</head>
<body>
    <div id="box" onclick="transitionBox(this);"></div>
</body>
</html>

Be sure to specify a duration for your transition using the transition-duration property. Otherwise, the duration of your transition will be zero, and you will not see an animation between the changes in state. For more information on CSS transitions, see the “How Transitions Work” section of the Safari Visual Effects Guide.

How do I use CSS animations to add animation to my web content?

CSS animations are a lot like CSS transitions, except that you have fine-grained control over the keyframes of the animation, and you can listen for DOM events to be notified of an animation's start, end, or iteration. CSS animations introduce the @keyframes rule to define animations. You can then use the name of the animation you've defined as the value of the animation-name property on other elements.

Listing 8 shows a simple example of CSS animation. For the first 50% of the animation, the box scales down to 30% of its original size. For the second half of the animation, the box scales back up to its full size. Note that this animation occurs over a duration of 4 seconds.

Listing 8: Using CSS animations to add animation.

<html>
<head>
<style>
    @-webkit-keyframes changeScale {
        0% {
            -webkit-transform: scale(1.0);
        }
        50% {
            -webkit-transform: scale(0.3);
        }
        100% {
            -webkit-transform: scale(1.0);
        }
    }

    #box {
        height: 300px;
        width: 300px;
        background-color: purple;
        -webkit-animation-name: changeScale;
        -webkit-animation-duration: 4s;
    }
</style>
</head>
<body>
    <div id="box"></div>
</body>
</html>

For more information about CSS animations, see the "How Animations Work" section of the Safari Visual Effects Guide.

How do I control the acceleration curve for a CSS transition or animation?

You can control the acceleration curve of a CSS transition or animation by specifying a timing function. By default, CSS transitions and animations use a timing function named ease, which is an acceleration curve that looks good in most situations. Other timing functions available are linear, ease-in, ease-out, ease-in-out. You can also specify control points for a cubic-bezier function for complete control of the transition or animation.

To specify an acceleration curve for a CSS animation, use the animation-timing-function property. For CSS transitions, use the transition-timing-function property. The code in Listing 9 specifies that the transition to make a box shrink to half its size and change color should be performed over an ease-in acceleration curve.

Listing 9: Using timing functions with CSS transitions.

<html>
<head>
<style>
    #box {
        -webkit-transform: scale(1.0);
        -webkit-transition-property: -webkit-transform, background-color;
        -webkit-transition-duration: 5s;
        -webkit-transition-timing-function: ease-in;
        background-color: green;
        border: 2px solid;
        height: 200px;
        width: 200px;
        }
</style>
<script>
    function transitionBox(box) {
        box.style.webkitTransform = 'scale(0.5)';
        box.style.backgroundColor = 'yellow';
    }
</script>
</head>
<body>
    <div id="box" onclick="transitionBox(this);"></div>
</body>
</html>

For more information on using timing functions for CSS transitions or animations, see the the “Using Timing Functions” sections of the Safari Visual Effects Guide and the Safari CSS Reference.

How do I detect when animations have started, iterated, or ended?

When animating elements on a webpage using CSS animations, you can detect through JavaScript when an animation has started, iterated, or ended using DOM events. The event names are webkitAnimationStart, webkitAnimationIteration, and webkitAnimationEnd. You can listen for these events just like you would any other event - either by adding a listener for the event to an element via addEventListener, or by adding an attribute directly to the element, such as onWebkitAnimationEnd. Listing 10 shows how to listen for all three events on a single animated element.

Listing 10: CSS animation event handlers.

<html>
<head>
<script>
    function addAnimationHandlers() {
        var box = document.getElementById('box');
        box.addEventListener('webkitAnimationStart', function (){ alert('Animation started.'); }, false);
        box.addEventListener('webkitAnimationIteration', function (){ alert('Animation iterated.'); }, false);
        box.addEventListener('webkitAnimationEnd', function (){ alert('Animation ended.'); }, false);
    }

</script>
<style>
    @-webkit-keyframes changeScale {
        0% {
            -webkit-transform: scale(1.0);
        }
        50% {
            -webkit-transform: scale(0.3);
        }
        100% {
            -webkit-transform: scale(1.0);
        }
    }
        #box {
                height: 300px;
                width: 300px;
                background-color: purple;
                -webkit-animation-name: changeScale;
                -webkit-animation-duration: 4s;
                -webkit-animation-iteration-count: 3;
        }
</style>
</head>
<body onload="addAnimationHandlers();">
    <div id="box"></div>
</body>
</html>

For more information on detecting when an animation has started, iterated, or ended, see the "Handling Animation Events" section of the Safari Visual Effects Guide.

How do I delay the start of a CSS transition or CSS animation?

Sometimes you may find it necessary to delay the start of a CSS transition or CSS animation—perhaps you have several elements with the same animation, but you
 want to stagger their start times. To add a delay to the beginning of your CSS animation, use the animation-delay property with a value specified in seconds. For CSS transitions use the transition-delay property, as illustrated in Listing 11.

Listing 11: Delaying the start of a CSS transition.

#box {
    -webkit-transform: scale(1.0);
    -webkit-transition-duration: 1.5s;
        -webkit-transition-property: -webkit-transform, background-color;
    -webkit-transition-delay: 2s;
    background-color: green;
    border: 2px solid;
    height: 200px;
    width: 200px;
}

For more information on delaying the start of a CSS transitions or animations, see the the “Setting Transition Properties” section of the Safari Visual Effects Guide and the Safari CSS Reference.

How do I repeat a CSS animation?

CSS transitions always execute only once, when the values of the properties being animated are changed via JavaScript or CSS. If you use CSS animations, you can specify that an animation iterate multiple times or even infinitely by using the animation-iteration-count property. The default value of this property is 1; integers or the keyword infinite are other possible values for this property. Listing 12 shows code to draw a box that shrinks to 30% of its size then grows back to its full size over a period of 4 seconds. Because the value of the animation-iteration-count property is infinite, this animation will repeat forever.

Listing 12: Repeating CSS animation.

<html>
<head>
<style>
    @-webkit-keyframes changeScale {
        0% {
            -webkit-transform: scale(1.0);
        }
        50% {
            -webkit-transform: scale(0.3);
        }
        100% {
            -webkit-transform: scale(1.0);
        }
    }

    #box {
        height: 300px;
        width: 300px;
        background-color: purple;
        -webkit-animation-name: changeScale;
        -webkit-animation-duration: 4s;
        -webkit-animation-iteration-count: infinite;
    }
</style>
</head>
<body>
    <div id="box"></div>
</body>
</html>

For more information on repeating CSS animations, see the "Repeating Animations" section of the Safari Visual Effects Guide and the Leaves sample code.

How do I embed a custom font in a webpage?

CSS web fonts provide a mechanism for you to use the font of your choice in your web content, without requiring that the font be installed on the computer on which the webpage is being viewed. To use a custom font in a webpage, first use the @font-face rule to define the name of your font family and the source URL for the font. Listing 13 illustrates this technique.

Listing 13: Defining a font with @font-face.

@font-face {
    font-family: "Tuffy";
    src: url("Tuffy_Bold.otf");
}

You can now use the font that you have defined as the value for the font-family property in other CSS definitions. Listing 14 uses the font that we defined in Listing 13 as the value for the font-family property in a CSS definition for second-level headings.

Listing 14: CSS definition that includes a custom web font.

h2 { 
    /* use the Tuffy font that we previously defined; serif will be the fallback */ 
    font-family: "Tuffy", serif; 
    color: #006699;
}

For more information about web fonts, see the "Supported CSS Rules" section of the Safari CSS Reference. The sample code PhotoToss: CSS Transforms, Transitions, and Web Fonts uses web fonts to display text.

How do I add a drop shadow to a webpage element?

You can use the CSS box-shadow property to specify a shadow effect that will be applied to the border box of an object, including complex objects such as table cells, inline elements that span multiple lines, and elements that use border-radius to define rounded corners. The box-shadow property takes four parameters: a horizontal offset for the shadow, a vertical offset for the shadow, a blur radius, and a color.

Listing 15 shows a CSS definition that defines a shadow on every cell of a table. The shadow stretches 3 pixels in the x-direction, 5 pixels in the y-direction, uses a blur radius of 5 pixels, and uses indigo for the color of the shadow with an opacity of 70 percent.

Listing 15: Adding a drop shadow to table cells.

td {
    border:1px solid black; 
    padding: 10px; 
    -webkit-box-shadow: 3px 5px 5px rgba(75, 0, 130, 0.7);
}

To add a drop shadow to text, you should use the text-shadow CSS property. The syntax for text-shadow and box-shadow are the same. For more information about both of these properties, see the Safari CSS Reference.

How do I add a gradient to a webpage element?

You can specify a linear or radial gradient for an element using the CSS gradient property. This property takes the following parameters: the type of gradient, points for the beginning and end of the gradient, and a color-stop function. Listing 16 defines a linear gradient that starts in the upper left corner and ends in the lower left corner. Its color-stop function uses the shorthand functions from and to to define a gradient that interpolates from purple to red.

Listing 16: A simple linear gradient.

<html>
<head>
<style>
    .purpleToRed {
        width:200px; 
        height:200px; 
        background: -webkit-gradient(linear, left top, left bottom, from(purple), to(red));
}
</style>
</head>
<body>
    <div class="purpleToRed"></div>
</body>
</html>

You can use CSS gradients anywhere that you would use an image. For instance, CSS gradients can be used for background-image, border-image, and list-style-image. For more information about CSS gradients see the Safari CSS Reference.

How do I add a reflection to a webpage element?

You can add a reflection to an element by using the CSS box-reflect property. This property takes three parameters: the direction of the reflection, the offset of the reflection, and a mask-box-image that can be used to overlay the reflection. The mask-box-image parameter is useful for adding, for example, a gradient to a reflection.

Listing 17 adds a reflection to a video. Since reflections update as the source changes, you will see the video playing in the reflection. This reflection will appear below the element, 4 pixels away from the original element. A CSS gradient is specified for the mask-box-image.

Listing 17: Adding a reflection to video.

<html>
<head>
<style>
.reflect {
-webkit-box-reflect: 
    below 4px 
    -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0.5, transparent), to(white))"; 
}
</style>
</head>
<body>
    <video src="iPod.mp4" class="reflect" />
</body>
</html>

For more information about CSS reflections, see the Safari CSS Reference.

How do I add an mask to a webpage element?

Safari and WebKit support a variety of CSS properties that give you fine-grained control over alpha masks. These properties are analogous to the background and border-image properties, and include properties such as mask, mask-origin, mask-image, and mask-repeat. Listing 18 masks a video with an image, so that the video is displayed in an oval shape.

Listing 18: Adding an oval mask to video.

<html>
<head>
<style>
.oval-mask {
    -webkit-mask-repeat: no-repeat; 
    -webkit-mask-image: url(oval.png); 
    -webkit-mask-position: center;
}
</style>
</head>
<body>
    <video src="iPod.mp4" class="oval-mask" />
</body>
</html>

For more information about CSS masks, see the Safari CSS Reference.



Document Revision History

Date Notes
2009-02-16 First Version
Back to Top



Did this document help you? Yes It's good, but... Not helpful...