Jim Lawless' Blog


A Scrolling Banner using Canvas and JavaScript

Originally published on: Wed, 02 Sep 2009 19:11:04 +0000

A couple weeks ago, I wrote the post Scrolling GIF Banners with PerlMagick. That post described how to build a simple scrolling text banner as an animated GIF.

Unfortunately, the technique requires some bandwidth; a new frame must be stored in the image for each sequence in the animation. It would be much easier if we could simply animate a graphic element so that it would scroll.

I suppose that with some manipulation of an IMG object's style attributes, we could change the topmost corner of the image so that we could move it around the screen and could produce a similar scrolling effect with a smaller amount of data.

The HTML5 Canvas object now makes this a more simple task. I have just begun to tinker with the Canvas object, so I decided to see what a scrolling image might look like.

In order to properly view this animation, your need to have a browser that supports the Canvas object. I happen to be using Mozilla Firefox 3.0.x.

First, let's take a look at a small, 16-color GIF file that has the message that we'd like to scroll to the left.

The above image is 682 pixels wide and 80 pixels high. The size of the image file is just over 5K.

Here's the code we'll use to scroll the image to the left in the canvas block.


<html><head /><body onload="loader()">
<script type="text/javascript">


// License: MIT / X11
// Copyright (c) 2009 by James K. Lawless
// jimbo@radiks.net http://www.radiks.net/~jimbo
// http://www.mailsend-online.com
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.



   var x=299,y=0;
   var msg=new Image();

   function loader() {
      msg.src="sample_message.gif";
      setInterval(anim,100);
   }

   function anim() {
      var ctx = document.getElementById('myCanvas').getContext('2d');
      ctx.clearRect(0,0,300,200);
      ctx.drawImage(msg,x,y);
      x-=5;
      if(x<(-683)) {
         x=299;
      }
   }
</script>
<div style="background-color: #cccccc;">
<h2>Scrolling an image on a canvas</h2>
<p>
<canvas style="margin-left: 15;" id="myCanvas" width="300" height="200">
</canvas>
</div>
</body></html>

Toward the bottom of the HTML markup, you'll notice the inclusion of the canvas tag. I have specified a with of 300 by 200 pixels. I have offset the element 15 pixels to the right by using a style alteration.

In the JavaScript code, I define variables x,y, and msg. x will represent the horizontal coordinate of the image in pixels. This variable is initialized to 299, the last horizontal pixel position of the defined canvas. The code later subtracts 5 from x until x is less than -683. ( I chose -683 because that would ensure the the 682-pixel image had scrolled completely off of the canvas area. )

Once x reaches some value below -683, the JavaScript code resets x to 299. The variable y really never changes for this experiment and could be replaced with the constant 0.

The variable msg represents the image that we want to scroll. msg is first constructed as an Image() DOM object. The src property of that object is later changed to "sample_message.gif".

A call to setInterval() causes the anim() function to execute repeatedly at a requested frequency of once every 100 milliseconds.

The anim() function first obtains a two-dimensional drawing context from the canvas element. Then, the code clears the canvas and begins drawing the image onto positions x and y. The variable x is adjusted for the next animation sequence and the function terminates.

You can observe a functioning sample of the above at this link:

http://www.mailsend-online.com/wp/canvas_scroll.htm

Unless otherwise noted, all code and text entries are Copyright ©2009 by James K. Lawless



Views expressed in this blog are those of the author and do not necessary reflect those of the author's employer. Views expressed in the comments are those of the responding individual.

stumbleupon Save to StumbleUpon
digg Digg it
reddit Save to Reddit
facebook Share on Facebook
twitter Share on Twitter
aolfav More bookmarks


Previous post: Changing the C64 Text Color in C
Next post:Internet Protocols and Rhino JavaScript


About Jim ...


Click **here**
to try out MailWrench;
a command-line SMTP /
SMTPS (Google Gmail)
mailer for Windows.


Follow me on Twitter

http://twitter.com/lawlessGuy


Recent Posts

A JavaScript REPL for Android Devices

MailSend is Free

My Blog Engine

The October 10th Bug

A Review of Kevin Mitnick's Book Ghost in the Wires

Spellbound by Web Programming

Backlinks to my Blog Posts

Play MP3 Files with Python on Windows


Random Posts

Preventing Windows Screen-Saver Activation

Twimmando No More

Along Came AWK

A Review of Kevin Mitnick's Book Ghost in the Wires

WSH2EXE part 2

Embedding JavaScript in a Batch File

Auto Save Clipboard Images Redux

Generating Primes with XSLT

Auto Save Images from the Clipboard

Obfuscated Perl


Full List of Posts

http://www.mailsend-online.com/bloglist.htm


Recent Posts from my Other Blog

Remembering Dr. San Guinary

Why Some Web Sites will go Dark on Jan 18th

SNL Superhero Skit

More Ruby Games

My Ruby Game Challenge Entry

Steal this Bookmarklet

Nerd Toys

Learn New Jargon, You Must

Spot the Wiebe

Tech Magazine Glory Days

Book Review : Paull Allen - Idea Man

A 90's Experiment in Online Systems - The U.S. West CommunityLink Service