English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML5 Canvas Drawing Rectangle

in HTML5One of the easiest shapes to draw on the canvas element is a rectangle. You can use2D context function fillRect() and operation strokeRect().

Online Example

in HTML5One of the easiest shapes to draw on the canvas element is a rectangle. You can use2D context function fillRect() and operation strokeRect(). Here is a simple example:

<canvas id="ex1" width="500" height="150" style="border: 1px solid #cccccc;">    
HTML5 Canvas not supported    
</canvas>    
<script>       
var canvas = document.getElementById("ex1");    
var context = canvas.getContext("2d");    
context.fillStyle = "#ff0000";    
context.fillRect(10,10, 100,100);    
context.strokeStyle = "#0000ff";    
context.strokeRect(30,20, 120,110);      
</script>
Test and see ‹/›

Line Width - lineWidth

You can use2Set the line width of the outlined rectangle using the properties of the D context. The method is as follows:

<canvas id="ex4" width="500" height="150" style="border: 1px solid #cccccc;">    
HTML5 Canvas not supported    
</canvas>    
<script>       
var canvas = document.getElementById("ex4");    
var context = canvas.getContext("2d");    
var x = 10;    
var y = 10;    
var width = 100;    
var height = 100;    
context.lineWidth = 4;    
context.strokeRect(x, y, width, height);      
</script>
Test and see ‹/›

This is the line width of4to change the appearance of the rectangle:

HTML5 Canvas not supported

Rectangle Color

You can use 2Set the drawing color of a rectangle using the fillStyle or strokeStyle properties of the D context. This is the first example, and these settings are displayed in bold:

<canvas id="ex5" width="500" height="150" style="border: 1px solid #cccccc;">    
HTML5 Canvas not supported    
</canvas>    
<script>       
var canvas = document.getElementById("ex5");    
var context = canvas.getContext("2d");    
context.fillStyle = "#ff0000";    
context.fillRect(10,10, 100,100);    
context.strokeStyle = "#0000ff";    
context.strokeRect(30,20, 120,110);    
</script>
Test and see ‹/›

This is the rectangle drawn again on the canvas:

HTML5 Canvas not supported