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:
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
context.fillStyle = 'yellow';
context.fillRect(0, 0, canvas.width, canvas.height / 2);
context.fillStyle = 'red';
context.fillRect(0, canvas.height / 2, canvas.width, canvas.height / 2);
1. Practical example
In this example, we present how to use fillRect()
method to fill the canvas
with two different colors.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
#my-canvas { border: 1px solid gray; }
</style>
</head>
<body>
<canvas id="my-canvas" width="200" height="200"></canvas>
<script>
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
context.fillStyle = 'yellow';
context.fillRect(0, 0, canvas.width, canvas.height / 2);
context.fillStyle = 'red';
context.fillRect(0, canvas.height / 2, canvas.width, canvas.height / 2);
</script>
</body>
</html>
2. Reusable function
In this section, we present a reusable function that fills the canvas
with two specified colors.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
#my-canvas { border: 1px solid gray; }
</style>
</head>
<body>
<canvas id="my-canvas" width="200" height="200"></canvas>
<script>
function fillCanvas(context, color1, color2) {
var middleY = canvas.height / 2;
context.fillStyle = color1;
context.fillRect(0, 0, canvas.width, middleY);
context.fillStyle = color2;
context.fillRect(0, middleY, canvas.width, middleY);
}
// Usage example:
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
fillCanvas(context, 'yellow', 'red');
</script>
</body>
</html>