Bits & Bytes

Clipping in JavaScript with Absolute Positioning

If you program games in JavaScript, you will often find it necessary to clip the region of an image that lies outside of the viewport. The solution is easy, but not obvious. The elements in a game are generally positioned using the “absolute” positioning designation: For example, the line = “absolute”; in the program below sets the positioning that the image of the Madonna, qrMadonna, refers to to absolute. (For an explanation of absolute positioning, see our post on positioning elements.)

Below, we have the code for an HTML file and a JavaScript file. The HTML file is essentially blank; it is simply used to call the JavaScript file, “ClipImage.js” and execute the code.

The file “ClipImage.js” contains four variables that refer to four nested HTML elements. The outermost element is the body; this element was created in the HTML file and is retrieved via a call to the getElementsByTagName() function, along with the array operator. After this, we create a div called qrOuterDiv to hold everything; this outer div is created to allow the code inside to flow normally, since it does not have absolute positioning (Otherwise, it is not needed.) The next element is qrInnerDiv, and it contains the image element that we are clipping; it is necessary that this element have its position as “absolute” and its overflow as “hidden”. Finally, the image element qrImage is 200×149 and is positioned at (125, 100) inside of the div, which is 300×200. So, the image hangs outside of the div by 25 and 49 pixels, respectively.

To illustrate this, we have an resulting image of what this clipping looks like below. The faint region that lies outside the dark gray rectangle is actually clipped. We show this region so that you can see what has been clipped. We also have the original image of the “Madonna and Child with Cherubs” that we used in the example, at the top of the article.

HTML File: “ClipImage.html”

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="" xml:lang="en" lang="en">
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>'s Javascript Clipping Example</title>
    <script type="text/javascript" src="ClipImage.js"></script>

JavaScript File: “ClipImage.js”

var qrBody;
var qrOuterDiv;
var qrInnerDiv;
var qrImage;

function PageLoaded() {
    // Get the main body element, first/only element of array
    qrBody = document.getElementsByTagName("body")[0];

    qrOuterDiv = document.createElement("div");

    qrInnerDiv = document.createElement("div"); = "#444444"; = "300px"; = "200px"; = "absolute"; = "hidden";

    qrImage = document.createElement("img");
    qrImage.src = "MadonnaAndChildWithCherubs.jpg"; = "absolute"; = "125px"; = "100px";

window.onload = PageLoaded;

Tags: , , , , , , , , , , , , ,

Michael Hall

By: Michael Hall

Leave a Reply



© 2007–2022 LLC. All rights reserved.