HTML and CSS Reference
In-Depth Information
Here we use the convenience method context.fillRect . This draws and fills a rectangle path in the
same way as our line drawing commands, but does not move the pen around much. Let's see how it all
looks together on the canvas in the document 07-gradient-fill-1.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Gradient Fill 1</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
pt1 = {x: 0, y: 0}, //gradient start point
pt2 = {x: 100, y: 100}, //gradient end point
gradient = context.createLinearGradient(pt1.x, pt1.y, pt2.x, pt2.y);
//gradient from white to red
gradient.addColorStop(0, "#ffffff");
gradient.addColorStop(1, "#ff0000");
context.fillStyle = gradient;
context.fillRect(0, 0, 100, 100);
};
</script>
</body>
</html>
Test this in your browser and you see a white-to-red gradient square. Now, let's draw the square in a
different location by altering the drawing code. Change the x and y position where you start the square (in
08-gradient-fill-2.html ):
context.fillRect(100, 100, 100, 100);
The square is all red, what happened? The gradient starts at point 0, 0 and ends at point 100, 100, which
is where the square begins. At this position, the gradient has already reached full red, and it's red from
there on out. So again, you want the x, y of the gradient to start at the top-left point of the shape, like so:
pt1 = {x: 100, y: 100}, //gradient start point
pt2 = {x: 200, y: 200}, //gradient end point
gradient = context.createLinearGradient(pt1.x, pt1.y, pt2.x, pt2.y);
Here, the starting point of the gradient is the same as the starting point of the square. Using the same square, you
can play around with gradient color stops to see what kind of effects you can create. First, try three colors:
//gradient from white to blue to red
gradient.addColorStop(0, "#ffffff");
gradient.addColorStop(0.5, "#0000ff");
gradient.addColorStop(1, "#ff0000");
Search WWH ::




Custom Search