WPF Graphics: Drawing a square using XAML

This entry is part 6 of 8 in the series WPF Graphics

Drawing a square using XAML.

The canvas.left and canvas.right position the location of the rectangle relative to the position of the canvas.

MainWindow.xaml

<Window x:Class="WpfApplication11.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication11"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Canvas Width="300" Height="300">
            <Rectangle Width="250" Height="250" Canvas.Left="20" Canvas.Top="20" Fill="LightBlue"/>
        </Canvas>
    </Grid>

MainWindow.xaml.cs

using System.Windows;

namespace WpfApplication11
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

square

HTML5 Canvas: Drawing and styling a rectangle or square in a canvas

This entry is part 4 of 17 in the series HTML5 Canvas

Using fillRect(pos-x, pos-y, width, height), we can draw a rectangle or square.

This next example will create a 100 pixel by 100 pixel square and place it in the top-left corner
(0,0) of the canvas

<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='utf-8'>
    <title>Codecrawl.com: Canvas rectangle</title>
    <style>
        canvas {
            border: 1px solid #000;
        }
    </style>
</head>
<body>
<canvas id='myCanvas' width='640' height='480'></canvas>
<script>
    var canvas = document.getElementById('myCanvas').getContext('2d');
    canvas.fillStyle='red';
    canvas.fillRect(0, 0, 100, 100);
</script>
</body>
</html>

The canvas.fillStyle=’red’ will fill the square red.