EN
JavaScript - fill canvas with two different colors vertically
0 points
In this article, we would like to show you how to fill a canvas with two different colors vertically 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 / 2, canvas.height); // fillRect(x, y, width, height)
6
7
context.fillStyle = 'red';
8
context.fillRect(canvas.width / 2, 0, canvas.width, canvas.height);
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 / 2, canvas.height); // fillRect(x, y, width, height)
19
20
context.fillStyle = 'red';
21
context.fillRect(canvas.width / 2, 0, canvas.width, canvas.height);
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
var myCanvas = document.querySelector('#my-canvas');
15
16
function fillCanvas(canvas, color1, color2) {
17
var context = canvas.getContext('2d');
18
19
context.fillStyle = color1;
20
context.fillRect(0, 0, canvas.width / 2, canvas.height); // fillRect(x, y, width, height)
21
22
context.fillStyle = color2;
23
context.fillRect(canvas.width / 2, 0, canvas.width, canvas.height);
24
}
25
26
fillCanvas(myCanvas, 'yellow', 'red');
27
28
</script>
29
</body>
30
</html>