📜  canvas fillrect - Javascript (1)

📅  最后修改于: 2023-12-03 15:14:05.768000             🧑  作者: Mango

Canvas fillRect - JavaScript

Canvas fillRect is a method used in JavaScript to draw a filled rectangle on an HTML canvas. This method is useful when creating various shapes, including bars, boxes, and other graphical objects.

Syntax
context.fillRect(x, y, width, height);
Parameters
  • x : The x-coordinate of the top-left corner of the rectangle.
  • y : The y-coordinate of the top-left corner of the rectangle.
  • width : The width of the rectangle.
  • height : The height of the rectangle.
Return value

This method does not return a value.

Example
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
context.fillStyle = '#FF0000';
context.fillRect(10, 10, 50, 50);
Explanation

In this example, we create a canvas element with an id of myCanvas and get its 2D context. We then set the fillStyle property of the context to red using hex code. Finally, we call the fillRect() method with the parameters x = 10, y = 10, width = 50 and height = 50. This draws a filled rectangle starting at point (10, 10) with a width of 50 pixels and a height of 50 pixels.

Conclusion

Canvas fillRect is a simple and effective way to draw filled rectangles on a canvas. It provides developers with a lot of options to create dynamic shapes and designs.