How to Draw a Chessboard in HTML Canvas Using JavaScript

The canvas HTML element provides a bitmap area for graphics drawing. The canvas was standardized across various browsers in the HTML5 specification. Using JavaScript, we can draw 2D/3D images and animation on a canvas. Almost all modern browsers support canvas. With a hardware accelerated browser, Canvas can produce fast 2D graphics.

The following tutorial is intended as an introduction to Canvas 2D drawing using JavaScript. We will draw a chess board using some of the basic drawing primitives available on the canvas element. See the Mozilla canvas tutorial for a detailed look at the canvas API.

Let us create a simple HTML file(index.html) which contains the canvas element. Using the script tag, we will import the the JavaScript file(chess.js) containing the drawing commands for chessboard. When the HTML file is opened in a browser, the onload event on the body tag is triggered. This in turn calls the JavaScript method drawChessboard() defined in the script tag of the HTML page. The full source code of the index.html is given below.

<html>
  <head>
    <meta charset="UTF-8">
    <title>Draw Chess Board</title>
    <script src="chess.js"></script>
  </head>
  <body onload="drawChessboard()">
    <canvas id="canvasChessboard" width="800px" height="500px"></canvas>
  </body>
</html>

Let us now create chess.js which contains the JavaScript code for drawing the chessboard. Ensure that you have chess.js and index.html in the same folder. The full source code of chess.js is given below,

function drawChessboard() {
  // size of each chess square
  const squareSize = 50;
  // position of board's top left
  const boardTopx = 50;
  const boardTopy = 50;
  let canvas = document.getElementById("canvasChessboard");
  context = canvas.getContext("2d");
  for(let i=0; i<8; i++) {
    for(let j=0; j<8; j++) {
      context.fillStyle = ((i+j)%2==0) ? "white":"black";
      let xOffset = boardTopx + j*squareSize;
      let yOffset = boardTopy + i*squareSize;
      context.fillRect(xOffset, yOffset, squareSize, squareSize);
    }
  }
  // draw the border around the chessboard
  context.strokeStyle = "black";
  context.strokeRect(boardTopx, boardTopy, squareSize*8, squareSize*8)
}

The drawChessboard() method gets a reference to the canvas element using the getElementById() method. We then create a 2d drawing context using the getContext() method of canvas object. Finally a nested loop draws all the 64 squares of the chess board. The squares are drawn using white or black color depending on the position of the square in the board.

The final output of the chessboard drawing JavaScript code is given below,
chessboard in javascript

How to Draw Rectangles and Squares Using Python Turtle

Python’s turtle package can be used to draw various shapes on a canvas. Turtle allows the programmer to move a pen in a specified direction by specifying its heading and distance. Turtle has no built-in primitive for drawing a rectangle or square. However it is easy to create a function to draw a rectangle(or square) in turtle.

The following python program defines a custom function for drawing rectangles using turtle. Note that the centre of the turtle canvas is at 0,0. Hence if you draw just a dot at (0,0) it will be at the centre of the drawing canvas. The function draw_rectangle() requires the co-ordinates of the top left of the rectangle. You also need to specify width, height, thickness and color of the rectangle.

The following example draws a blue rectangle which is 200 pixels in width and 100 pixels in height. We have specified the top left of the rectangle as (-100,50) to position the rectangle at the centre of the canvas. The rectangle drawn has a thickness of 5 pixels.

import turtle
turtle.setup(500,500)
board = turtle.Turtle()

# draws a rectangle given top left position of a rectangle
def draw_rectangle(board,x,y,width,height,size,color):
  board.pencolor(color)
  board.pensize(size)
  board.setheading(0)

  board.up()
  board.goto(x,y)
  board.down()
  # draw top
  board.forward(width)
  # draw right
  board.right(90)
  board.forward(height)
  # draw bottom
  board.right(90)
  board.forward(width)
  # draw left
  board.right(90)
  board.forward(height)
  board.end_fill()


# in turtle, the centre of the canvas is 0,0
# hence we position the rectangle in the center
# note that we need to pass the top left co-ordinates of rectangle
# draws rectangle with 200 pixels in width and 100 pixels in height
draw_rectangle(board,-100,50,200,100,5,"blue")
turtle.done()

The following the sample output from the program,

Following python program is a different version which also allows us to specify a fill color for the rectangle. The example is identical to the previous one except that we use a different color to fill the rectangle.

import turtle
turtle.setup(500,500)
board = turtle.Turtle()

# draws a rectangle given top left position of a rectangle
def draw_filled_rectangle(board,x,y,width,height,size,color,fill):
  board.fillcolor(fill)
  board.pencolor(color)
  board.pensize(size)
  board.setheading(0)

  board.begin_fill()
  board.up()
  board.goto(x,y)
  board.down()
  # draw top
  board.forward(width)
  # draw right
  board.right(90)
  board.forward(height)
  # draw bottom
  board.right(90)
  board.forward(width)
  # draw left
  board.right(90)
  board.forward(height)
  board.end_fill()


# in turtle, the centre of the canvas is 0,0
# hence we position the rectangle in the center
# note that we need to pass the top left co-ordinates of rectangle
# draws rectangle with 200 pixels in width and 100 pixels in height
# also specifies the rectangle color and the fill color
draw_filled_rectangle(board,-100,50,200,100,5,"blue","green")
turtle.done()

The following the sample output from the program showing a filled rectangle,

The following program uses looping to draw a two dimensional matrix of identical black squares. Note that we are using black as fill color and white as the stroke color for the rectangles.

import turtle
turtle.setup(500,500)
board = turtle.Turtle()

# draws a rectangle given top left position of a rectangle
def draw_filled_rectangle(board,x,y,width,height,size,color,fill):
  board.fillcolor(fill)
  board.pencolor(color)
  board.pensize(size)
  board.setheading(0)

  board.begin_fill()
  board.up()
  board.goto(x,y)
  board.down()
  # draw top
  board.forward(width)
  # draw right
  board.right(90)
  board.forward(height)
  # draw bottom
  board.right(90)
  board.forward(width)
  # draw left
  board.right(90)
  board.forward(height)
  board.end_fill()

# draw a 7x7 matrix of black squares
for x in range(1,8):
  for y in range(1,8):
    draw_filled_rectangle(board,-200+x*20,y*20,20,20,2,"white","black")

turtle.done()

The following the sample output of 7×7 matrix of black squares from the python turtle program,

How to Draw Circles Using Python Turtle

Python contains an interesting drawing module called Turtle. This module is available as part of the standard python distribution. Turtle consists of a number of graphics operations modelled after pen drawing. In this article I will show you how we can use the turtle commands to draw circle based shapes.

How to Draw a Simple Circle Using Python Turtle

The following python script creates a simple circle with default color at the center of the turtle canvas. We have defined the turtle canvas with a width of 800 pixels and a height of 600 pixels. We then draw a circle of radius 100 pixels in the middle of the canvas. Note that the bottom of the circle is placed in the middle of the canvas.

import turtle

turtle.setup(800,600)
board = turtle.Turtle()

board.penup()
board.setpos(0,0)
board.pendown()
board.circle(100)

turtle.done()

How to Draw a Face Using Python Turtle

The following python script draws the shape of a face using the turtle commands. We have organized the code in functions so that each section of the drawing is separate. Note that we are resetting the direction of the pen after drawing part of a circle in the draw_lip functions.

import turtle
turtle.setup(800,600)
board = turtle.Turtle()

def draw_face():
  board.penup()
  board.setpos(0,0)
  board.pendown()
  board.circle(100)

def draw_left_eye():
  board.penup()
  board.setpos(-50,100)
  board.pendown()
  board.circle(25)

def draw_right_eye():
  board.penup()
  board.setpos(50,100)
  board.pendown()
  board.circle(25)

def draw_right_lip():
  board.penup()
  board.setpos(0,25)
  board.pendown()
  board.circle(100,45)
  board.setheading(0)

def draw_left_lip():
  board.penup()
  board.setpos(0,25)
  board.pendown()
  board.circle(100,-45)
  board.setheading(0)

draw_face()
draw_left_eye()
draw_right_eye()
draw_left_lip()
draw_right_lip()

board.penup()
board.setpos(400,400)
turtle.done()

How to Draw Tangent Circles Using Python Turtle

The following python program creates tangent circles at the middle of the canvas. We use a loop to generate the circles and for each iteration we just change the radius of the circle.

import turtle
turtle.setup(800,600)
board = turtle.Turtle()

for i in range(1,20):
  board.circle(i*10)

turtle.done()

How to Draw Concentric Circles Using Python Turtle

The following python program creates concentric circles at the middle of the canvas. We use a loop to generate the circles and for each iteration we change the y location and the radius of the circle.

import turtle
turtle.setup(800,600)
board = turtle.Turtle()

for i in range(1,20):
  board.circle(i*10)
  board.penup()
  board.sety(-i*10)
  board.pendown()

turtle.done()

How to Draw Olympics Logo Using Python Turtle

The following python program creates the olympics logo using the the turtle package. It also demonstrates the use of pen color and pen size in drawing shapes.

import turtle
turtle.setup(800,600)
board = turtle.Turtle()


circle_positions = [(-120,0,"blue"), (0,0,"black"), (120,0,"red"),
                    (-60,-60,"yellow"), (60,-60,"green")]

for pos in circle_positions:
  board.penup()
  board.setpos(pos[0],pos[1])
  board.pencolor(pos[2])
  board.pensize(5)
  board.pendown()
  board.circle(50)

turtle.done()

How to Create Canvas Animation Using Tkinter

Tkinter is one of the most popular GUI toolkits available for python. It is available as part of the standard python installation. Hence you can use this package without installing any additional modules. Tkinter is a powerful GUI library and you can use it to build full fledged user interfaces or build simple desktop games.

This article contains a step by step guide on building an animation using the python tkinter package. We will be using canvas object of the tkinter package to draw our animation. Note that the following program requires python 3.6 or above.

The following python program creates a simple animation showing the movement of a ball across the screen. Following are the steps in the program,

  • Create and display main window of the application
  • Create and attach the canvas to the main window. We will be drawing to this canvas
  • Draw and animate a circle (our ball) inside the canvas

Let us start by importing tkinter and time modules. We will use time module to introduce a delay for drawing successive screens of the animation,

import tkinter
import time

Let us now create a set of variables for our animation demo. This defines the size of our gaming canvas, speed of the ball, size of the ball and where we want our ball to start moving from.

# width of the animation window
animation_window_width=800
# height of the animation window
animation_window_height=600
# initial x position of the ball
animation_ball_start_xpos = 50
# initial y position of the ball
animation_ball_start_ypos = 50
# radius of the ball
animation_ball_radius = 30
# the pixel movement of ball for each iteration
animation_ball_min_movement = 5
# delay between successive frames in seconds
animation_refresh_seconds = 0.01

The following function creates the application window with the specified title and dimensions,

# The main window of the animation
def create_animation_window():
  window = tkinter.Tk()
  window.title("Tkinter Animation Demo")
  # Uses python 3.6+ string interpolation
  window.geometry(f'{animation_window_width}x{animation_window_height}')
  return window

We then create a function to create the animation canvas and attach it to the main window,

# Create a canvas for animation and add it to main window
def create_animation_canvas(window):
  canvas = tkinter.Canvas(window)
  canvas.configure(bg="black")
  canvas.pack(fill="both", expand=True)
  return canvas

Let us now create a function to create and animate a circle in an infinite loop. We use the create_oval method to create a circle(ball) with specified radius and draw it on canvas. We move the ball until it reaches a boundary and then we reverse the direction of the ball. Note the use of move method of canvas which lets us move a drawing in the canvas to another location. Also note the use of python array unpacking to get the location of the ball.

# Create and animate ball in an infinite loop
def animate_ball(window, canvas,xinc,yinc):
  ball = canvas.create_oval(animation_ball_start_xpos-animation_ball_radius,
            animation_ball_start_ypos-animation_ball_radius,
            animation_ball_start_xpos+animation_ball_radius,
            animation_ball_start_ypos+animation_ball_radius,
            fill="blue", outline="white", width=4)
  while True:
    canvas.move(ball,xinc,yinc)
    window.update()
    time.sleep(animation_refresh_seconds)
    ball_pos = canvas.coords(ball)
    # unpack array to variables
    xl,yl,xr,yr = ball_pos
    if xl < abs(xinc) or xr > animation_window_width-abs(xinc):
      xinc = -xinc
    if yl < abs(yinc) or yr > animation_window_height-abs(yinc):
      yinc = -yinc

Finally let us call all the functions in order to run our animation,

# The actual execution starts here
animation_window = create_animation_window()
animation_canvas = create_animation_canvas(animation_window)
animate_ball(animation_window,animation_canvas, animation_ball_min_movement, animation_ball_min_movement)

Full code of the python animation demo using tkinter is given below. This can be easily extended to a bat and ball game if you know event handling in tkinter. Save the following code in “tkinter-draw-demo.py” file and then run the command “python3 tkinter-draw-demo.py” to see the animation.

import tkinter
import time

# width of the animation window
animation_window_width=800
# height of the animation window
animation_window_height=600
# initial x position of the ball
animation_ball_start_xpos = 50
# initial y position of the ball
animation_ball_start_ypos = 50
# radius of the ball
animation_ball_radius = 30
# the pixel movement of ball for each iteration
animation_ball_min_movement = 5
# delay between successive frames in seconds
animation_refresh_seconds = 0.01

# The main window of the animation
def create_animation_window():
  window = tkinter.Tk()
  window.title("Tkinter Animation Demo")
  # Uses python 3.6+ string interpolation
  window.geometry(f'{animation_window_width}x{animation_window_height}')
  return window

# Create a canvas for animation and add it to main window
def create_animation_canvas(window):
  canvas = tkinter.Canvas(window)
  canvas.configure(bg="black")
  canvas.pack(fill="both", expand=True)
  return canvas

# Create and animate ball in an infinite loop
def animate_ball(window, canvas,xinc,yinc):
  ball = canvas.create_oval(animation_ball_start_xpos-animation_ball_radius,
            animation_ball_start_ypos-animation_ball_radius,
            animation_ball_start_xpos+animation_ball_radius,
            animation_ball_start_ypos+animation_ball_radius,
            fill="blue", outline="white", width=4)
  while True:
    canvas.move(ball,xinc,yinc)
    window.update()
    time.sleep(animation_refresh_seconds)
    ball_pos = canvas.coords(ball)
    # unpack array to variables
    xl,yl,xr,yr = ball_pos
    if xl < abs(xinc) or xr > animation_window_width-abs(xinc):
      xinc = -xinc
    if yl < abs(yinc) or yr > animation_window_height-abs(yinc):
      yinc = -yinc

# The actual execution starts here
animation_window = create_animation_window()
animation_canvas = create_animation_canvas(animation_window)
animate_ball(animation_window,animation_canvas, animation_ball_min_movement, animation_ball_min_movement)

How to Download Multiple Files Concurrently in Python

Python has a very powerful library called requests for initiating http requests programmatically. You can use requests for downloading files hosted over http protocol. Run the following command to install requests python library. This assumes that you already have python 3 installed on your system.

pip3 install requests

You may need to prefix the above command with sudo if you get permission error in your linux system.

The following python 3 program downloads a given url to a local file. The following example assumes that the url contains the name of the file at the end and uses it as the name for the locally saved file.

import requests

def download_url(url):
  # assumes that the last segment after the / represents the file name
  # if the url is http://abc.com/xyz/file.txt, the file name will be file.txt
  file_name_start_pos = url.rfind("/") + 1
  file_name = url[file_name_start_pos:]

  r = requests.get(url, stream=True)
  if r.status_code == requests.codes.ok:
    with open(file_name, 'wb') as f:
      for data in r:
        f.write(data)

# download a sngle url
# the file name at the end is used as the local file name
download_url("https://jsonplaceholder.typicode.com/posts")

After running the above program, you will find a file named “posts” in the same folder where you have the script saved.

The following python 3 program downloads a list of urls to a list of local files. However the download may take sometime since it is executed sequentially.

import requests

def download_url(url):
  print("downloading: ",url)
  # assumes that the last segment after the / represents the file name
  # if url is abc/xyz/file.txt, the file name will be file.txt
  file_name_start_pos = url.rfind("/") + 1
  file_name = url[file_name_start_pos:]

  r = requests.get(url, stream=True)
  if r.status_code == requests.codes.ok:
    with open(file_name, 'wb') as f:
      for data in r:
        f.write(data)

# download a sngle url
# the file name at the end is used as the local file name
download_url("https://jsonplaceholder.typicode.com/posts")
download_url("https://jsonplaceholder.typicode.com/comments")
download_url("https://jsonplaceholder.typicode.com/photos")
download_url("https://jsonplaceholder.typicode.com/todos")
download_url("https://jsonplaceholder.typicode.com/albums")

The download program above can be substantially speeded up by running them in parallel. The following python program shows how to download multiple files concurrently by using multiprocessing library which has support for thread pools. Note the use of results list which forces python to continue execution until all the threads are complete. Without the iteration of the results list, the program will terminate even before the threads are started. Also note that we are running 5 threads concurrently in the script below and you may want to increase it if you have a large number of files to download. However, this puts substantial load on the server and you need to be sure that the server can handle such concurrent loads.

import requests
from multiprocessing.pool import ThreadPool

def download_url(url):
  print("downloading: ",url)
  # assumes that the last segment after the / represents the file name
  # if url is abc/xyz/file.txt, the file name will be file.txt
  file_name_start_pos = url.rfind("/") + 1
  file_name = url[file_name_start_pos:]

  r = requests.get(url, stream=True)
  if r.status_code == requests.codes.ok:
    with open(file_name, 'wb') as f:
      for data in r:
        f.write(data)
  return url


urls = ["https://jsonplaceholder.typicode.com/posts",
        "https://jsonplaceholder.typicode.com/comments",
        "https://jsonplaceholder.typicode.com/photos",
        "https://jsonplaceholder.typicode.com/todos",
        "https://jsonplaceholder.typicode.com/albums"
        ]

# Run 5 multiple threads. Each call will take the next element in urls list
results = ThreadPool(5).imap_unordered(download_url, urls)
for r in results:
    print(r)