Bits & Bytes

Posts Tagged ‘web’

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 qrMadonna.style.position = “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"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>XoaX.net's Javascript Clipping Example</title>
</head>
<body>
    <script type="text/javascript" src="ClipImage.js"></script>
</body>
</html>

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");
    qrBody.appendChild(qrOuterDiv);

    qrInnerDiv = document.createElement("div");
    qrInnerDiv.style.backgroundColor = "#444444";
    qrInnerDiv.style.width = "300px";
    qrInnerDiv.style.height = "200px";
    qrInnerDiv.style.position = "absolute";
    qrInnerDiv.style.overflow = "hidden";
    qrOuterDiv.appendChild(qrInnerDiv);

    qrImage = document.createElement("img");
    qrImage.src = "MadonnaAndChildWithCherubs.jpg";
    qrImage.style.position = "absolute";
    qrImage.style.left = "125px";
    qrImage.style.top = "100px";
    qrInnerDiv.appendChild(qrImage);
}

window.onload = PageLoaded;

Three Ways to Apply CSS Styles: Inline, Embedded, and External

There are three ways to apply a style to an HTML element: Inline, Embedded, and External. Below, I demonstrate each of these methods by applying a single style to the same element three times. The necessary code is shown in bold.

(Proverbs 6:16-19) There are six things the Lord hates, seven that are detestable to him: haughty eyes, a lying tongue, hands that shed innocent blood, a heart that devises wicked schemes, feet that are quick to rush into evil, a false witness who pours out lies and a person who stirs up conflict in the community.

Inline

The inline method is most suitable for setting the style on a single element. This is because the inline method requires us to repeat the entire specification for each element on which we want to apply it. Also, if we want to change the style, we must change it on each element. If you are setting the style for multiples elements, you should consider using either the embedded or external style sheet method.

To use the inline method, simply add style=”<< style specification >>” to the element that you want to style, where << style specification >> is the CSS style that you want to apply. For example, the element above would be written as:

<div style=”width:420px; height:120px; padding:20px; margin:30px; background-color:#ffddcc; color:#885522;“>(Proverbs 6:16-19) There are six things the Lord hates, seven that are detestable to him: haughty eyes, a lying tongue, hands that shed innocent blood, a heart that devises wicked schemes, feet that are quick to rush into evil, a false witness who pours out lies and a person who stirs up conflict in the community.</div>

Embedded

The embedded style sheet method is most suitable for setting the style for a many elements in the same document. With this method, we define a style specification as a class inside the head element and give it a name. Then we can apply the style repeatedly in the document by using the defined class inside each of the desired elements.

To use an embedded style sheet, define all styles in a style tag inside the head, as shown below. In this case, we have defined a class called “prog.” The style associate with this class can be used by adding class=”prov” to a tag, as shown in the example code below. This class can be applied to any number of elements in the document, and the usage of the class allows us to subsequently change the style for all of the elements just by simply changing the class style definition.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
<head>
    <title>CSS Applying a Style</title>

    <style>
        .prov {
            width:420px;
            height:120px;
            padding:20px;
            margin:30px;
            background-color:#ffddcc;
            color:#885522;
        }
    </style>

</head>

<body>
<div class=”prov”>(Proverbs 6:16-19) There are six things the Lord hates, seven that are detestable to him: haughty eyes, a lying tongue, hands that shed innocent blood, a heart that devises wicked schemes, feet that are quick to rush into evil, a false witness who pours out lies and a person who stirs up conflict in the community.</div>
</body>
</html>

External

The external style sheet is most suitable for setting a style that is used over multiple documents. Like the embedded style sheet, the external style sheet allows us to change all of the defined styles by making a single change to the style definition. However, the external style sheet uses a separate file to define the style so that it can be used in several files at once.

To use an external style sheet, create a file with a .css extension and put whatever style definitions you would like inside it. Below, I show an example with a file named “MyStyles.css” with the external style specification in it. In the HTML document, we need to add the line <link rel=”stylesheet” type=”text/css” href=”MyStyles.css” /> inside the head tag. This link tag can be used inside as many HTML documents as you would like. Then we only need to add class=”prov” to any element that we want to style, just as we did with the embedded style sheet. Note that in this example, we have the HTML document and the .css file in the same directory. However, if we want to put the style sheet file (the .css file) in a separate directory, we need to add the path to the href.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
<head>
    <title>CSS Applying a Style</title>
    <link rel=”stylesheet” type=”text/css” href=”MyStyles.css” />
</head>

<body>
<div class=”prov”>(Proverbs 6:16-19) There are six things the Lord hates, seven that are detestable to him: haughty eyes, a lying tongue, hands that shed innocent blood, a heart that devises wicked schemes, feet that are quick to rush into evil, a false witness who pours out lies and a person who stirs up conflict in the community.</div>
</body>
</html>

MyStyles.css

.prov {
    width:420px;
    height:120px;
    padding:20px;
    margin:30px;
    background-color:#ffddcc;
    color:#885522;
}

Using an External JavaScript File

Putting JavaScript into a separate file has many advantages over writing the code inline in an HTML file. First, it makes the JavaScript code much cleaner since the HTML code is in a separate file. Second, it helps to promote modularization, which is always a benefit in programming. Finally, it the eliminates the need for creating CDATA sections to encapsulate JavaScript code that contains XHTML characters; we will explain this more later

Beginning with the code from our earlier JavaScript post, we have a simple HTML file, which I have called “JavaScriptBasis.html” in this post. The original HTML code with the embedded JavaScript code looks like this:

Old JavaScriptBasis.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <title>XoaX.net</title>
</head>
<body>

<script type="text/javascript">
    document.write("Welcome to XoaX.net!");
</script>

</body>
</html>

What we want to do now is remove the JavaScript code, put it into a separate .js file, and call it via the script tag from the HTML file. To do this, use your favorite text editor to create a .js file called “BasicWrite.js” in the same directory as your HTML file and save it with this code pasted into it:

BasicWrite.js

document.write("Welcome to XoaX.net!");

Then open the file “JavaScriptBasis.html” and change code in the script tags to this:

<script type="text/javascript" src="BasicWrite.js"></script>

Now, your HTML file will call your JavaScript file. The code in the HTML file should look like this:

JavaScriptBasis.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <title>XoaX.net</title>
</head>
<body>

<script type="text/javascript" src="BasicWrite.js"></script>

</body>
</html>

After you have saved the new files, double-click the HTML file to open it and you should see the message “Welcome to XoaX.net!” printed just as you did before.

It may not feel like much has been accomplished yet. In fact, it might seem like we have made the code more complex. However, the advantages will become more apparent when we write bigger programs.

Finally, we remark that using .js files allows us to eliminate the need to use CDATA sections. When XHMTL characters, like <, are used inside of an embedded JavaScript section, they create validation problems. For example, in order to allow this code to validate, we need the CDATA section as shown here:

CDATA Section


<script type="text/javascript">
var iX = 10;
/*<![CDATA[*/
if (iX < 13) {
    document.write("Welcome to XoaX.net!");
}
]]>
/*]]>*/
</script>

When this code is put into an external JavaScript, this CDATA section is not needed for validation. Note that the CDATA section looks particularly horrific since it requires us to comment out both endpoints of the CDATA section so that it does not adversely affect the JavaScript code:
. . .
/*<![CDATA[*/
. . .
/*]]>*/
. . .

 

© 2007–2024 XoaX.net LLC. All rights reserved.