Languages
[Edit]
EN

JavaScript - fill canvas with two different colors vertically

0 points
Created by:
Iona
415

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>

 

References

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

Alternative titles

  1. JavaScript - multiple vertical 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