User:AChaves/The Red Rectangle

From HTML5 Builder
Jump to: navigation, search

In this tutorial we are going to start using the Canvas component to draw 2D images, animate them, and interact with them.

Drawing

Create a server page and, from the Design view, drop a Canvas component on the Designer from the Tool Palette. Adjust its size and position however you like.

The Canvas component is basically a surface where you can draw using client-side code. In order to do that, select the Canvas component in the Object Inspector and, from the Javascript tab, double-click the OnPaint event. Inside the resulting event handler, you will define the drawing of the content of the canvas. We are going to use the OnPaint event handler to define the commands for the drawing of a red rectangle centered in the canvas:

?>
//begin js

    // Get the context and the Canvas component.
    context = event;
    canvas = $('#Canvas1').get()[0];

    // Define the background color of the Canvas, using a rectangle with the same width and height.
    context.fillStyle = "#000000";
    context.fillRect(0,0,canvas.width,canvas.height);

    // Define a rectangle with half the height and width of the canvas, and centered on it.
    context.fillStyle = "#FF0000";
    context.fillRect(canvas.width*.25,canvas.height*.25,canvas.width*.50,canvas.height*.50);

//end
<?php

First, we hold in the context variable (you can call it however you like, ctx is a commonly used name) a reference to the context of the canvas, which can be used to run any methods to draw in the canvas. The OnPaint event provides the context through the event parameter, but you can also access the context from anywhere using the global variable ComponentName_ctx (in our example, AChaves/The Red Rectangle1_ctx).

Then, we do the same for the Canvas component itself. We get a jQuery object for it ($('#AChaves/The Red Rectangle1')), and then the pure DOM element we will work with (.get()[0]).

Finally, we use two combinations of the following methods:

  • fillStyle() is used to define the fill color, to be used in the next drawing with filling performed on the context.
  • fillRect() is used to draw a rectangle with the current fill color, and the specified limits: x and y for the position of the top-left corner, and the width and height of the rectangle.

We use the first pair of calls to draw a black background for the canvas. Here a background is actually a rectangle that shares its dimensions with those of the Canvas component.

The second pair of calls draws a red rectangle with half the size of the canvas, and centered.

The result:

{TODO| Image: CanvasTutorial1.png}}

Animation

Interaction