EN
JavaScript - fill canvas with two different colors horizontally
0 points
In this article, we would like to show you how to fill a canvas with two different colors horizontally using JavaScript.
Quick solution:
xxxxxxxxxx
1
var canvas = document.querySelector('#my-canvas');
2
var context = canvas.getContext('2d');
3
4
context.fillStyle = 'yellow';
5
context.fillRect(0, 0, canvas.width, canvas.height / 2);
6
7
context.fillStyle = 'red';
8
context.fillRect(0, canvas.height / 2, canvas.width, canvas.height / 2);
In this example, we present how to use fillRect()
method to fill the canvas
with two different colors.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
#my-canvas { border: 1px solid gray; }
7
8
</style>
9
</head>
10
<body>
11
<canvas id="my-canvas" width="200" height="200"></canvas>
12
<script>
13
14
var canvas = document.querySelector('#my-canvas');
15
var context = canvas.getContext('2d');
16
17
context.fillStyle = 'yellow';
18
context.fillRect(0, 0, canvas.width, canvas.height / 2);
19
20
context.fillStyle = 'red';
21
context.fillRect(0, canvas.height / 2, canvas.width, canvas.height / 2);
22
23
</script>
24
</body>
25
</html>
In this section, we present a reusable function that fills the canvas
with two specified colors.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
#my-canvas { border: 1px solid gray; }
7
8
</style>
9
</head>
10
<body>
11
<canvas id="my-canvas" width="200" height="200"></canvas>
12
<script>
13
14
function fillCanvas(context, color1, color2) {
15
var middleY = canvas.height / 2;
16
context.fillStyle = color1;
17
context.fillRect(0, 0, canvas.width, middleY);
18
context.fillStyle = color2;
19
context.fillRect(0, middleY, canvas.width, middleY);
20
}
21
22
23
// Usage example:
24
25
var canvas = document.querySelector('#my-canvas');
26
var context = canvas.getContext('2d');
27
28
fillCanvas(context, 'yellow', 'red');
29
30
</script>
31
</body>
32
</html>