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:
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
context.fillStyle = 'yellow';
context.fillRect(0, 0, canvas.width / 2, canvas.height); // fillRect(x, y, width, height)
context.fillStyle = 'red';
context.fillRect(canvas.width / 2, 0, canvas.width, canvas.height);
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 / 2, canvas.height); // fillRect(x, y, width, height)
context.fillStyle = 'red';
context.fillRect(canvas.width / 2, 0, canvas.width, canvas.height);
</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>
var myCanvas = document.querySelector('#my-canvas');
function fillCanvas(canvas, color1, color2) {
var context = canvas.getContext('2d');
context.fillStyle = color1;
context.fillRect(0, 0, canvas.width / 2, canvas.height); // fillRect(x, y, width, height)
context.fillStyle = color2;
context.fillRect(canvas.width / 2, 0, canvas.width, canvas.height);
}
fillCanvas(myCanvas, 'yellow', 'red');
</script>
</body>
</html>