Languages
[Edit]
EN

JavaScript - fill canvas with two different colors horizontally

0 points
Created by:
nickkk0
647

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>

 

References

  1. CanvasRenderingContext2D.fillRect() - Web APIs | MDN

Alternative titles

  1. JavaScript - multiple horizontal background colors for HTML canvas
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - HTML5 canvas tutorial

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join