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

del_icio_us Save to del.icio.us
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


Search this Blog (and site)

Search this Site with PicoSearch


Subscribe to this Blog

 Subscribe!


Contact Me

Email: jimbo@radiks.net


Follow me on Twitter

http://twitter.com/lawlessGuy


Recent Posts

Mad Schemes : Learning Lisp via SICP

Auto Save Clipboard Images Redux

Extending SpiderMonkey JavaScript on Windows

Rhino JavaScript to EXE with launch4j

Compiling Rhino JavaScript to Java

Directory Traversal in Rhino JavaScript

Taking Shape

We've Moved!


Popular Posts

A Command-Line MP3 Player for Windows

Auto Save Images from the Clipboard

Java in a Windows EXE with launch4j

An Interview with Tom Zimmer: Forth System Developer

Setting Windows Console Text Colors in C


Random Posts

Structuring my Thinking

Stacking Images with PerlMagick

FIF Isn't Forth

PHP, Transparent GIF's, and Web Tracking

The Protection Racket

Yet Another Enhanced Echo Command

A Simple Parser for a Small Command Line Interface

A DSL in JavaScript

Shrouding CSharp and Java Source Code with AWK

Jim Butterfield : The Commodore Guru


Full List of Posts

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


Blogroll

MicroISV on a Shoestring
DadHacker
The Bottom Feeder
Writin' That Code!
The Recursive ISV
The Thomsen Blog
Prototypically Speaking
The Reinvigorated Programmer