Draw a rectangle in HTML5 Canvas, html5canvas

Source: Internet
Author: User

Draw a rectangle in HTML5 Canvas, html5canvas
This article describes how to draw a rectangle in HTML5 Canvas. This article uses three APIs: fillRect, strokeRect, and clearRect. For more information, see

This article is translated from Steve Fulton & Jeff Fulton HTML5 Canvas, Chapter 2, "The Basic Rectangle Shape ".

Let's take a look at the simple ry built in Canvas-rectangle painting. There are three ways to draw a rectangle in a Canvas: fillRect, StrokeRect, and clearRect ). Of course, we can also use "paths" to depict all images including rectangles.

The following are APIs of the above three methods:

1. fillRect (x, y, width, height ). Draw a solid rectangle starting from (x, y) with width and height.
2. strokeRect (x, y, width, height ). Draw a rectangle frame starting from (x, y) with width and height. The rectangle is rendered into different styles Based on the strokeStyle, lineWidth, lineJoin, and miterLimit attributes currently set.
3. clearRect (x, y, width, height ). Clear the rectangular area with width and height starting from (x, y) to make it completely transparent.

Before calling the above method to draw a Canvas, we need to set the style of filling and stroke. The most basic way to set these styles is to use a 24-bit color (represented by a hexadecimal string ). The following is a simple example:

The Code is as follows:
Context. fillStyle = "#000000 ";
Context. strokeStyle = "# ff00ff ";

In the following example, the fill color is set to black, and the stroke color is set to purple:

The Code is as follows:
Function drawScreen (){
Context. fillStyle = "#000000 ";
Context. strokeStyle = "# ff00ff ";
Context. lineWidth = 2;
Context. fillRect (10, 10, 40, 40 );
Context. strokeRect (0, 0, 60, 60 );
Context. clearRect (20, 20, 20, 20 );
}

Shows the code execution result:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.