HTML and CSS Reference
In-Depth Information
To set the fill color of your rectangle, you set the
fillStyle
property on the context to the desired color. This col-
or should be specified using a standard color format, such as a hexadecimal, rgb (red, green, blue), or rgba (red,
green, blue, alpha) color code. You can also use color keywords such as
red
,
blue
, and
green
.
ctx.fillStyle = “rgba(0,0,0,0.4)";
Here the fill color has been set to a semitransparent black. The alpha value controls the opacity. Setting the alpha
value to 1 will cause the color to be opaque whereas setting it to 0 will cause it to be fully transparent.
The code in this exercise can be found in folder 4.
Here are the steps to draw your rectangle:
1.
Open the
adscript.js
file in your text editor.
2.
Create a new function called
drawAdvert()
underneath the
if
statement that checks for Canvas support.
This is where you are going to write all the code that draws on the canvas. The reason for putting this code
in its own function will become clear toward the end of this chapter.
window.onload = function() {
var adCanvas = document.getElementById(“adCanvas");
if (adCanvas.getContext) {
// Initialize a 2d drawing context.
var ctx = adCanvas.getContext(“2d");
}
function drawAdvert() {
}
}
3.
Call this
drawAdvert()
function after you initialize the
ctx
variable.
if (adCanvas.getContext) {
// Initialize a 2d drawing context.
var ctx = adCanvas.getContext(“2d");
drawAdvert();
}
4.
Within the
drawAdvert()
function, set the
fillStyle
to use the color:
rgba(0,0,0,0.4)
.
function drawAdvert() {
// Create the Background Rectangle
ctx.fillStyle = “rgba(0,0,0,0.4)";
}
5.
Now use the
fillRect()
function to draw the rectangle on the canvas. You want the rectangle to fill the
whole canvas, so set the
x
and
y
parameters to 0, the
width
to 600, and the
height
to 150.
function drawAdvert() {
// Create the Background Rectangle