canvas basic learning notes

Colors, styles, and shadows

attributedescribe
fillStyleSets or returns the color, gradient, or mode used to fill a painting
strokeStyleSets or returns the color, gradient, or mode used for strokes
shadowColorSets or returns the color used for shadows
shadowBlurSets or returns the level of blur used for shadows
shadowOffsetXSets or returns the horizontal distance of the shadow from the shape
shadowOffsetYSets or returns the vertical distance of the shadow from the shape
methoddescribe
createLinearGradient()

Create a linear gradient (used on canvas content)

JavaScript syntax:

context.createLinearGradient(x0,y0,x1,y1);
 var c = document.getElementById("myCanvas");
      var ctx = c.getContext("2d");
      var grd = ctx.createLinearGradient(0, 0, 170, 0); 
      grd.addColorStop(0, "black");
      grd.addColorStop(0.5, "red");
      grd.addColorStop(1, "white");
      ctx.fillStyle = grd;
      ctx.fillRect(20, 20, 150, 75);

Parameter value

parameterdescribe
x0The x coordinate of the ramp start point
y0y coordinate of gradient start point
x1The x coordinate of the gradient end point
y1y coordinate of gradient end point
createPattern()

Repeats the specified element in the specified direction

JavaScript syntax:

context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");
 // direction:'repeat''repeat-x''repeat-y''no-repeat'
      var c = document.getElementById("myCanvas");
      var ctx = c.getContext("2d");
      ctx.clearRect(0, 0, c.width, c.height);
      var img = document.getElementById("lamp");
      var pat = ctx.createPattern(img, direction);
      ctx.rect(0, 0, 150, 100);
      ctx.fillStyle = pat;
      ctx.fill();

Parameter value

parameterdescribe
imageSpecify the picture, canvas, or video element to use.
repeat

Default. The pattern repeats horizontally and vertically.

repeat-x

This mode repeats only horizontally.

repeat-y

This mode repeats only in the vertical direction.

no-repeat

This mode is displayed only once (not repeated).

createRadialGradient()

Create radial / circular gradient (used on canvas content)

JavaScript syntax:

context.createRadialGradient(x0,y0,r0,x1,y1,r1);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var grd=ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
ctx.fillStyle=grd;
ctx.fillRect(10,10,150,100);

Parameter value

parameterdescribe
x0The x coordinate of the start circle of the gradient
y0y coordinate of the start circle of the gradient
r0Radius of the starting circle
x1The x coordinate of the end circle of the gradient
y1y coordinate of the end circle of the gradient
r1Radius of end circle
addColorStop()

Specifies the color and stop position in the gradient object

JavaScript syntax:

gradient.addColorStop(stop,color);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

var grd=ctx.createLinearGradient(0,0,170,0);
grd.addColorStop(0,"black");
grd.addColorStop("0.3","magenta");
grd.addColorStop("0.5","blue");
grd.addColorStop("0.6","green");
grd.addColorStop("0.8","yellow");
grd.addColorStop(1,"red");

ctx.fillStyle=grd;
ctx.fillRect(20,20,150,100);

Parameter value

parameterdescribe
stopValues between 0.0 and 1.0 represent the position between the beginning and end of the ramp.
colorCSS color value displayed at the end

Line style

attributedescribe
lineCap

Sets or returns the end style of the line

Definition and Usage

The lineCap property sets or returns the style of the line cap at the end of the line.

Note: "round" and "square" make the line slightly longer.

Default:butt
JavaScript syntax:context.lineCap="butt|round|square";
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

ctx.beginPath();
ctx.lineWidth=10;
ctx.lineCap="butt";
ctx.moveTo(20,20);
ctx.lineTo(200,20);
ctx.stroke();

ctx.beginPath();
ctx.lineCap="round";
ctx.moveTo(20,40);
ctx.lineTo(200,40);
ctx.stroke();

ctx.beginPath();
ctx.lineCap="square";
ctx.moveTo(20,60);
ctx.lineTo(200,60);
ctx.stroke();

Attribute value

valuedescribe
buttDefault. Add a straight edge to each end of the line.
roundAdd a circular cap to each end of the line.
squareAdd a square cap to each end of the line.
lineJoin

Sets or returns the type of corner created when two lines intersect

Definition and Usage

The lineJoin property sets or returns the type of corner created when two lines meet.

Note: the value "miter" is restricted miterLimit Property.

Default:miter
JavaScript syntax:context.lineJoin="bevel|round|miter";

Attribute value

valuedescribe
bevel

Create a bevel.

round

Create a fillet.

miter

Default. Create sharp corners.

lineWidth

Sets or returns the current line width

Definition and Usage

The lineWidth property sets or returns the width of the current line in pixels.

Default:1
JavaScript syntax:context.lineWidth=number;

Attribute value

valuedescribe
numberThe width of the current line, in pixels.
miterLimit

Sets or returns the maximum miter length

Definition and Usage

The miterLimit property sets or returns the maximum miter length.

Miter length refers to the distance between the inner and outer corners at the intersection of two lines.

Tip: miterLimit is valid only when the lineJoin attribute is "miter".

The smaller the angle of the corner, the greater the miter length.

To avoid the miter length being too long, we can use the miterLimit attribute.

If the miter length exceeds the value of miterLimit, the edges and corners will be displayed in the "bevel" type of lineJoin (Figure 3):

Default:10
JavaScript syntax:context.miterLimit=number;

Attribute value

valuedescribe
number

Positive number. Specify the maximum miter length.

If the miter length exceeds the value of miterLimit, the edges and corners are displayed as "bevel" type of lineJoin.

rectangle

methoddescribe
rect()

create rectangles

Definition and Usage

The rect() method creates a rectangle.

Tip: please use stroke() Or fill() Method to actually draw a rectangle on the canvas.

JavaScript syntax:

context.rect(x,y,width,height);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

// Red rectangle
ctx.beginPath();
ctx.lineWidth="6";
ctx.strokeStyle="red";
ctx.rect(5,5,290,140);
ctx.stroke();

// Green rectangle
ctx.beginPath();
ctx.lineWidth="4";
ctx.strokeStyle="green";
ctx.rect(30,30,50,50);
ctx.stroke();

// Blue rectangle
ctx.beginPath();
ctx.lineWidth="10";
ctx.strokeStyle="blue";
ctx.rect(50,50,150,80);
ctx.stroke();

Parameter value

parameterdescribe
xThe x coordinate of the upper left corner of the rectangle
yy coordinate of the upper left corner of the rectangle
widthThe width of the rectangle in pixels
heightThe height of the rectangle in pixels
fillRect()

Draws a filled rectangle

Definition and Usage

The fillRect() method draws a "filled" rectangle. The default fill color is black.

Tip: please use fillStyle Property to set the color, gradient, or mode used to fill the drawing.

JavaScript syntax:

context.fillRect(x,y,width,height);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillRect(20,20,150,100);

Parameter value

parameterdescribe
xThe x coordinate of the upper left corner of the rectangle
yy coordinate of the upper left corner of the rectangle
widthThe width of the rectangle in pixels
heightThe height of the rectangle in pixels
strokeRect()

Draw rectangle (no fill)

Definition and Usage

The strokeRect() method draws a rectangle (without coloring). The default color for strokes is black.

Tip: please use strokeStyle Property to set the color, gradient, or mode of the stroke.

JavaScript syntax:

context.strokeRect(x,y,width,height);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();

Parameter value

parameterdescribe
xThe x coordinate of the upper left corner of the rectangle
yy coordinate of the upper left corner of the rectangle
widthThe width of the rectangle in pixels
heightThe height of the rectangle in pixels
clearRect()

Clears the specified pixel within the given rectangle

Definition and Usage

The clearRect() method clears the specified pixel within a given rectangle.

JavaScript syntax:

context.clearRect(x,y,width,height);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="red";
ctx.fillRect(0,0,300,150);
ctx.clearRect(20,20,100,50);

Parameter value

parameterdescribe
xThe x coordinate of the upper left corner of the rectangle to be cleared
yThe y coordinate of the upper left corner of the rectangle to be cleared
widthThe width of the rectangle to be cleared, in pixels
heightThe height of the rectangle to be cleared, in pixels

route

methoddescribe
fill()

Fill current drawing (path)

Definition and Usage

The fill() method fills the current image (path). The default color is black.

Tip: use the fillStyle property to fill another color / gradient.

Note: if the path is not closed, the fill() method adds a line from the end point to the start point of the path to close the path, and then fills the path.

JavaScript syntax:

context.fill();
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.fillStyle="green";
ctx.fill();

stroke()

Draw a defined path

Definition and Usage

The stroke() method actually draws the path defined by the moveTo() and lineTo() methods. The default color is black.

Tip: please use strokeStyle Property to draw another color / gradient.

JavaScript syntax:

context.stroke();
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(20,100);
ctx.lineTo(70,100);
ctx.strokeStyle="green";
ctx.stroke();

beginPath()

Start a path, or reset the current path

Definition and Usage

The beginPath() method starts a path or resets the current path.

Tip: use these methods to create paths: moveTo(), lineTo(), quadricCurveTo(), bezierCurveTo(), arcTo(), and arc().

Tip: please use stroke() Method to draw the exact path on the canvas.

JavaScript syntax:

context.fillRect(x,y,width,height);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

ctx.beginPath();
ctx.lineWidth="5";
ctx.strokeStyle="red"; // Red path
ctx.moveTo(0,75);
ctx.lineTo(250,75);
ctx.stroke(); // Draw

ctx.beginPath();
ctx.strokeStyle="blue"; // Blue path
ctx.moveTo(50,0);
ctx.lineTo(150,130);
ctx.stroke(); // Draw

moveTo()

Move the path to the specified point in the canvas without creating a line

Definition and Usage

The fillRect() method draws a "filled" rectangle. The default fill color is black.

Tip: please use stroke() Method to draw the exact path on the canvas.

JavaScript syntax:

context.moveTo(x,y);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(300,150);
ctx.stroke();

closePath()

Creates a path from the current point back to the starting point

Definition and Usage

The closePath() method creates a path from the current point to the start point.

Tip: please use stroke() Method to draw the exact path on the canvas.

Tip: please use fill() Method to fill the image (black by default). Please use fillStyle Property to fill another color / gradient.

JavaScript syntax:

context.closePath();
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(20,100);
ctx.lineTo(70,100);
ctx.closePath();
ctx.stroke();

lineTo()

Add a new point, and then create a line from that point to the last specified point in the canvas

Definition and Usage

The lineTo() method adds a new point and creates a line from that point to the last specified point in the canvas (this method does not create a line).

Tip: please use stroke() Method to draw the exact path on the canvas.

JavaScript syntax:

context.lineTo(x,y);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(300,150);
ctx.stroke();

Parameter value

parameterdescribe
xThe x coordinate of the target location of the path
yThe y coordinate of the target location of the path
clip()

Cut an area of any shape and size from the original canvas

Definition and Usage

The clip() method cuts any shape and size from the original canvas.

Tip: once an area is cut, all subsequent drawings will be limited to the cut area (other areas on the canvas cannot be accessed). You can also save the current canvas area by using the save() method before using the clip() method, and restore it at any time later (through the restore() method).

JavaScript syntax:

context.clip();
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
// Draw a rectangle
ctx.rect(50,20,200,120);
ctx.stroke();
// Draw red rectangle
ctx.fillStyle="green";
ctx.fillRect(0,0,150,100);
</script> 

<br />

<p>use clip(): </p>
<canvas id="myCanvas2" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
var c=document.getElementById("myCanvas2");
var ctx=c.getContext("2d");
// Clip a rectangular area
ctx.rect(50,20,200,120);
ctx.stroke();
ctx.clip();
// Draw red rectangle after clip()
ctx.fillStyle="green";
ctx.fillRect(0,0,150,100);

quadraticCurveTo()

Create a quadratic Bezier curve

Definition and Usage

The quadraticCurveTo() method adds a point to the current path by using the specified control point representing the quadratic Bezier curve.

Tip: a quadratic Bezier curve requires two points. The first point is the control point used in quadratic Bessel calculation, and the second point is the end point of the curve. The start point of the curve is the last point in the current path. If the path does not exist, use beginPath() And moveTo() Method to define the start point.

  • Starting point: moveTo(20,20)
  • Control point: quadraticcurveto (20100200,20)
  • End point: quadraticcurveto (20100200,20)

Tip: please check bezierCurveTo() method . It has two control points, not one.

JavaScript syntax:

context.quadraticCurveTo(cpx,cpy,x,y);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.quadraticCurveTo(20,100,200,20);
ctx.stroke();

Parameter value

parameterdescribe
cpxx coordinate of Bezier control point
cpyy coordinate of Bezier control point
xx coordinate of the end point
yy coordinate of the end point
bezierCurveTo()

Create cubic Bezier curve

Definition and Usage

The bezierCurveTo() method adds a point to the current path by using the specified control point representing the cubic Bezier curve.

Tip: cubic Bezier curve requires three points. The first two points are the control points used in cubic Bessel calculation, and the third point is the end point of the curve. The start point of the curve is the last point in the current path. If the path does not exist, use beginPath() And moveTo() Method to define the start point.

  • Starting point: moveTo(20,20)
  • Control point 1: bezierCurveTo (20100200100200,20)
  • Control point 2: bezierCurveTo (20100200100200,20)
  • End point: bezierCurveTo (20100200100200,20)

Tip: please check quadraticCurveTo() method . It has one control point, not two.

JavaScript syntax:

context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y);

Parameter value

parameterdescribe
cp1xx coordinate of the first Bezier control point
cp1yy coordinate of the first Bezier control point
cp2xx coordinate of the second Bezier control point
cp2yy coordinate of the second Bezier control point
xx coordinate of the end point
yy coordinate of the end point
arc()

Create arcs / curves (for creating circles or partial circles)

Definition and Usage

The arc() method creates an arc / curve (used to create a circle or part of a circle).

Tip: to create a circle through arc(), set the start angle to 0 and the end angle to 2 * math PI.

Tip: please use stroke() Or fill() Method to draw an actual arc on the canvas.

  • Center: arc(100,75,50,0*Math.PI,1.5*Math.PI)
  • Starting angle: arc(100,75,50,0,1.5*Math.PI)
  • End angle: arc(100,75,50,0*Math.PI,1.5*Math.PI)

JavaScript syntax:

context.arc(x,y,r,sAngle,eAngle,counterclockwise);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(100,75,50,0,2*Math.PI);
ctx.stroke();

Parameter value

parameterdescribe
xThe x coordinate of the center of the circle.
yThe y coordinate of the center of the circle.
rThe radius of the circle.
sAngleStarting angle, in radians. (the three o'clock position of the circle of the arc is 0 degrees).
eAngleEnd angle, in radians.
counterclockwiseOptional. Specifies whether the drawing should be counterclockwise or clockwise. False = clockwise, true = counterclockwise. (default is false)
arcTo()

Creates an arc / curve between two tangents

Definition and Usage

The arcTo() method creates an arc / curve between two tangents on the canvas.

Tip: use the stroke() method to draw the exact arc on the canvas.

JavaScript syntax:

context.fillRect(x1,y1,x2,y2,r);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.beginPath();
ctx.moveTo(20,20);           // Create start point
ctx.lineTo(100,20);          // Create horizontal lines
ctx.arcTo(150,20,150,70,50); // Create arc
ctx.lineTo(150,120);         // Create vertical lines
ctx.stroke();                // Draw

Parameter value

parameterdescribe
x1The x coordinate of the starting point of the arc
y1y coordinate of the starting point of the arc
x2The x coordinate of the end point of the arc
y2y coordinate of the end point of the arc
rRadius of arc
isPointInPath()

Returns true if the specified point is in the current path; otherwise, returns false

Definition and Usage

The isPointInPath() method returns true if the specified point is in the current path; Otherwise, false is returned.

JavaScript syntax:

context.isPointInPath(x,y);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
if (ctx.isPointInPath(20,50)){
   ctx.stroke();
};

Parameter value

parameterdescribe
xx coordinate of the test
yy coordinate of the test

transformation

methoddescribe
scale()

Zooms the current drawing to a larger or smaller size

Definition and Usage

The scale() method scales the current drawing, larger or smaller.

Note: if you scale the drawing, all subsequent drawings will also be scaled. Positioning is also scaled. If you scale(2,2), the drawing will be positioned twice as far from the upper left corner of the canvas.

JavaScript syntax:

context.scale(scalewidth,scaleheight);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.strokeRect(5,5,25,15);
ctx.scale(2,2);
ctx.strokeRect(5,5,25,15);
ctx.scale(2,2);
ctx.strokeRect(5,5,25,15);
ctx.scale(2,2);
ctx.strokeRect(5,5,25,15);

Parameter value

parameterdescribe
scalewidthScale the width of the current drawing (1 = 100%, 0.5 = 50%, 2 = 200%, and so on)
scaleheightScale the height of the current drawing (1=100%, 0.5=50%, 2=200%, etc.)
rotate()

Rotate current drawing

Definition and Usage

The rotate() method rotates the current drawing.

JavaScript syntax:

context.rotate(angle);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rotate(20*Math.PI/180);
ctx.fillRect(50,20,100,50);

Parameter value

parameterdescribe
angle

Rotation angle in radians.

To convert an angle to radians, use degrees * math Pi / 180 formula.

For example, if you need to rotate 5 degrees, you can specify the following formula: 5 * math PI/180.

translate()

Remap (0,0) position on canvas

Definition and Usage

The translate() method remaps the (0,0) position on the canvas.

Note: when you call a method such as fillRect() after translate(), the value is added to the x and y coordinates.

JavaScript syntax:

context.translate(x,y);
In position (10,10) Draw a rectangle at the new (0,0) Position set to (70,70). Draw the new rectangle again (note that the rectangle is now in position (80,80) Start drawing:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillRect(10,10,100,50);
ctx.translate(70,70);
ctx.fillRect(10,10,100,50);

Parameter value

parameterdescribe
xThe value added to the horizontal coordinate (x)
yThe value added to the vertical coordinate (y)
transform()

Replace the current conversion matrix of the drawing

Definition and Usage

Each object on the canvas has a current transformation matrix.

The transform() method replaces the current transform matrix. It operates the current transformation matrix with the matrix described below:

a  c  e
b  d  f
0  0  1

In other words, transform() allows you to scale, rotate, move, and tilt the current environment.

Note: this transformation only affects the drawing after the transform() method call.

Note: the behavior of the transform() method is relative to other transformations completed by rotate(), scale(), translate(), or transform(). For example, if you have set the drawing to double, the transform () method will double the drawing, and your drawing will eventually be quadrupled.

Tip: please check setTransform() Method, which does not behave relative to other transformations.

JavaScript syntax:

context.transform(a,b,c,d,e,f);

Draw a rectangle; Add a new transformation matrix through transform() and draw the rectangle again; Add a new transformation matrix and draw the rectangle again. Note that whenever you call transform (), it builds on the previous transform matrix:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

ctx.fillStyle="yellow";
ctx.fillRect(0,0,250,100)

ctx.transform(1,0.5,-0.5,1,30,10);
ctx.fillStyle="red";
ctx.fillRect(0,0,250,100);

ctx.transform(1,0.5,-0.5,1,30,10);
ctx.fillStyle="blue";
ctx.fillRect(0,0,250,100);

Parameter value

parameterdescribe
aScale drawing horizontally
bHorizontal tilt drawing
cVertical tilt drawing
dScale drawing vertically
eMove drawing horizontally
fMove drawing vertically
setTransform()

Resets the current conversion to the identity matrix. Then run transform()

Definition and Usage

Each object on the canvas has a current transformation matrix.

The setTransform() method resets the current transformation matrix to the identity matrix, and then runs with the same parameters transform().

In other words, setTransform() allows you to scale, rotate, move, and tilt the current environment.

Note: this transformation only affects the drawing after the setTransform() method call.

JavaScript syntax:

context.setTransform(a,b,c,d,e,f);

Draw a rectangle, reset and create a new transformation matrix through setTransform(), draw the rectangle again, reset and create a new transformation matrix, and then draw the rectangle again. Note that whenever you call setTransform(), it resets the previous transformation matrix and constructs a new matrix. Therefore, in the following example, the red rectangle will not be displayed because it is below the blue rectangle:

 

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

ctx.fillStyle="yellow";
ctx.fillRect(0,0,250,100)

ctx.setTransform(1,0.5,-0.5,1,30,10);
ctx.fillStyle="red";
ctx.fillRect(0,0,250,100);

ctx.setTransform(1,0.5,-0.5,1,30,10);
ctx.fillStyle="blue";
ctx.fillRect(0,0,250,100);

 

 

Parameter value

parameterdescribe
aRotate drawing horizontally
bHorizontal tilt drawing
cVertical tilt drawing
dScale drawing vertically
eMove drawing horizontally
fMove drawing vertically

text

attributedescribe
font

Sets or returns the current font property of the text content

Definition and Usage

Font attribute sets or returns the current font attribute of the text content on the canvas.

font attribute uses the same syntax as CSS font properties Same.

Default:10px sans-serif
JavaScript syntax:context.font="italic small-caps bold 12px arial";

Attribute value

valuedescribe
font-style

Specifies the font style. Possible values:

  • normal
  • italic
  • oblique
font-variant

Specify font variants. Possible values:

  • normal
  • small-caps
font-weight

Specifies the font weight. Possible values:

  • normal
  • bold
  • bolder
  • lighter
  • 100
  • 200
  • 300
  • 400
  • 500
  • 600
  • 700
  • 800
  • 900
font-size / line-heightSpecify font size and line height in pixels.
font-familySpecifies the font family.
captionUse the font of the Title Control (such as buttons, drop-down lists, etc.).
iconUse the font used to mark the icon.
menuUse fonts used in menus (drop-down lists and menu lists).
message-boxUse the font used in the dialog box.
small-captionUse the font used to mark small controls.
status-barUse the font used in the status bar of the window.
textAlign

Sets or returns the current alignment of the text content

Definition and Usage

The textAlign property sets or returns the current alignment of the text content based on the anchor point.

Normally, the text starts at the specified position, but if you set textAlign="right" and place the text at position 150, it ends at position 150.

Tip: use fillText() Or strokeText() Method actually draws and locates text on the canvas.

Default:start
JavaScript syntax:context.textAlign="center|end|left|right|start";
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

// Create a red line in position 150
ctx.strokeStyle="blue";
ctx.moveTo(150,20);
ctx.lineTo(150,170);
ctx.stroke();

ctx.font="15px Arial";    

// Show the different textAlign values
ctx.textAlign="start";      
ctx.fillText("textAlign=start",150,60);        
ctx.textAlign="end";      
ctx.fillText("textAlign=end",150,80);                  
ctx.textAlign="left";      
ctx.fillText("textAlign=left",150,100);
ctx.textAlign="center";     
ctx.fillText("textAlign=center",150,120);              
ctx.textAlign="right";      
ctx.fillText("textAlign=right",150,140);

 

Attribute value

valuedescribe
startDefault. The text starts at the specified location.
endThe text ends at the specified location.
centerThe center of the text is placed in the specified position.
leftAlign text left.
rightAlign text right.
textBaseline

Sets or returns the current text baseline used when drawing text

Definition and Usage

The textBaseline property sets or returns the current text baseline when text is drawn.

The following illustration illustrates the various baselines supported by the textBaseline attribute:

notes: fillText() Or strokeText() Method uses the specified textBaseline value when positioning text on the canvas.

Default:alphabetic
JavaScript syntax:context.textBaseline="alphabetic|top|hanging|middle|ideographic|bottom";
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

//Draw a blue line at position y=100
ctx.strokeStyle="blue";
ctx.moveTo(5,100);
ctx.lineTo(395,100);
ctx.stroke();

ctx.font="20px Arial"

//Place each word with a different textBaseline value at y=200
ctx.textBaseline="top";
ctx.fillText("Top",5,100);
ctx.textBaseline="bottom";
ctx.fillText("Bottom",50,100);
ctx.textBaseline="middle";
ctx.fillText("Middle",120,100);
ctx.textBaseline="alphabetic";
ctx.fillText("Alphabetic",190,100);
ctx.textBaseline="hanging";
ctx.fillText("Hanging",290,100);

Attribute value

valuedescribe
alphabeticDefault. Text baseline is a common letter baseline.
topThe text baseline is the top of the em box..
hangingThe text baseline is a hanging baseline.
middleThe text baseline is the middle of the em box.
ideographicText baseline is ideographic baseline.
bottomThe text baseline is the bottom of the em box.
methoddescribe
fillText()

Draw the filled text on the canvas

Definition and Usage

The fillText() method draws the colored text on the canvas. The default color for text is black.

Tip: please use font Property to define the font and size, and use fillStyle Property renders the text in another color / gradient.

JavaScript syntax:

context.fillText(text,x,y,maxWidth);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

ctx.font="20px Georgia";
ctx.fillText("Hello World!",10,50);

ctx.font="30px Verdana";
// Create gradient
var gradient=ctx.createLinearGradient(0,0,c.width,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","red");
// Fill with gradient
ctx.fillStyle=gradient;
ctx.fillText("w3school.com.cn",10,90);

Parameter value

parameterdescribe
textSpecifies the text to output on the canvas.
xThe x-coordinate position (relative to the canvas) where the text begins to be drawn.
yThe y-coordinate position (relative to the canvas) where the text begins to be drawn.
maxWidthOptional. The maximum text width allowed, in pixels.
strokeText()

Draw text on canvas (no fill)

Definition and Usage

The strokeText() method draws text (without coloring) on the canvas. The default color for text is black.

Tip: please use font Property to define the font and size, and use strokeStyle Property renders the text in another color / gradient.

JavaScript syntax:

context.strokeText(text,x,y,maxWidth);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

ctx.font="20px Georgia";
ctx.strokeText("Hello World!",10,50);

ctx.font="30px Verdana";
// Create gradient
var gradient=ctx.createLinearGradient(0,0,c.width,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","red");
// Fill with gradient
ctx.strokeStyle=gradient;
ctx.strokeText("w3school.com.cn",10,90);

Parameter value

parameterdescribe
textSpecifies the text to output on the canvas.
xThe x-coordinate position (relative to the canvas) where the text begins to be drawn.
yThe y-coordinate position (relative to the canvas) where the text begins to be drawn.
maxWidthOptional. The maximum text width allowed, in pixels.
measureText()

Returns an object containing the specified text width

Definition and Usage

The measureText() method returns an object that contains the specified font width in pixels.

Tip: use this method if you need to know the width of the text before it is output to the canvas.

JavaScript syntax:

context.measureText(text).width;
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="30px Arial";
var txt="Hello World"
ctx.fillText("width:" + ctx.measureText(txt).width,10,50)
ctx.fillText(txt,10,100);

Parameter value

parameterdescribe
textText to measure.

Image rendering

methoddescribe
drawImage()

Draw an image, canvas, or video onto the canvas

Definition and Usage

The drawImage() method draws an image, canvas, or video on the canvas.

The drawImage() method can also draw some parts of the image and / or increase or decrease the size of the image.

JavaScript syntax 1

Position the image on the canvas:

context.drawImage(img,x,y);

JavaScript syntax 2

Position the image on the canvas and specify the width and height of the image:

context.drawImage(img,x,y,width,height);

JavaScript syntax 3

Cut the image and locate the cut part on the canvas:

context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);

Parameter value

parameterdescribe
imgSpecify the image, canvas, or video to use.
sxOptional. The x-coordinate position at which to start cutting.
syOptional. The y coordinate position at which to start cutting.
swidthOptional. The width of the cut image.
sheightOptional. The height of the cut image.
xPlace the x coordinate position of the image on the canvas.
yPlace the y coordinate position of the image on the canvas.
widthOptional. The width of the image to use. (stretch or shrink image)
heightOptional. The height of the image to use. (stretch or shrink image)

Pixel operation

attributedescribe
width

Returns the width of the ImageData object

Definition and Usage

The width property returns the width of the ImageData object in pixels.

Tip: see createImageData(),getImageData() And putImageData() Method to get more knowledge about ImageData objects.

Default:#000000
JavaScript syntax:imgData.width;
height

Returns the height of the ImageData object

Definition and Usage

The height property returns the height of the ImageData object in pixels.

Tip: see createImageData(),getImageData() And putImageData() Method to get more knowledge about ImageData objects.

Default:#000000
JavaScript syntax:imgData.height;
data

Returns an object that contains the image data of the specified ImageData object

Definition and Usage

The fillStyle property sets or returns the color, gradient, or mode used to fill a painting.

The data property returns an object that contains the image data of the specified ImageData object.

For each pixel in the ImageData object, there are four aspects of information, namely RGBA value:

  • R - red (0-255)
  • G - green (0-255)
  • B - Blue (0-255)
  • A - alpha channel (0-255; 0 is transparent and 255 is fully visible)

color/alpha exists as an array and is stored in the data property of the ImageData object.

example:

Syntax for turning the first pixel in the ImageData object red:

imgData=ctx.createImageData(100,100);

imgData.data[0]=255;
imgData.data[1]=0;
imgData.data[2]=0;
imgData.data[3]=255;

Syntax for turning the second pixel in the ImageData object green:

imgData=ctx.createImageData(100,100);

imgData.data[4]=0;
imgData.data[5]=255;
imgData.data[6]=0;
imgData.data[7]=255;

Tip: see createImageData(),getImageData() And putImageData() Method to get more knowledge about ImageData objects.

JavaScript syntax:

imageData.data;
methoddescribe
createImageData()

Create a new, blank ImageData object

Definition and Usage

The createImageData() method creates a new blank ImageData object. The default pixel value for new objects is transparent black.

For each pixel in the ImageData object, there are four aspects of information, namely RGBA value:

  • R - red (0-255)
  • G - green (0-255)
  • B - Blue (0-255)
  • A - alpha channel (0-255; 0 is transparent and 255 is fully visible)

Therefore, transparent black means (0,0,0,0).

color/alpha exists as an array, and since the array contains four pieces of information for each pixel, the size of the array is four times that of the ImageData object. (an easier way to get the array size is to use ImageDataObject.data.length)

An array containing color/alpha information is stored in the of the ImageData object data Property.

Tip: after the operation completes the color/alpha information in the array, you can use putImageData() Method copies the image data back to the canvas.

example:

This syntax changes the first pixel in the ImageData object to red:

imgData=ctx.createImageData(100,100);

imgData.data[0]=255;
imgData.data[1]=0;
imgData.data[2]=0;
imgData.data[3]=255;

This syntax changes the second pixel in the ImageData object to red:

imgData=ctx.createImageData(100,100);

imgData.data[4]=0;
imgData.data[5]=255;
imgData.data[6]=0;
imgData.data[7]=255;

JavaScript syntax

There are two versions of the createImageData() method:

1. Create a new ImageData object at the specified size (in pixels):

var imgData=context.createImageData(width,height);

2. Create a new ImageData object with the same size as another specified ImageData object (image data will not be copied):

var imgData=context.createImageData(imageData);

Parameter value

parameterdescribe
widthThe width of the ImageData object, in pixels.
heightThe height of the ImageData object, in pixels.
imageDataAnother ImageData object.
getImageData()

Returns an ImageData object that copies pixel data for the rectangle specified on the canvas

Definition and Usage

The getImageData() method returns an ImageData object that copies the pixel data of the specified rectangle on the canvas.

For each pixel in the ImageData object, there are four aspects of information, namely RGBA value:

  • R - red (0-255)
  • G - green (0-255)
  • B - Blue (0-255)
  • A - alpha channel (0-255; 0 is transparent and 255 is fully visible)

color/alpha exists as an array and is stored in the of the ImageData object data Property.

Tip: after the operation completes the color/alpha information in the array, you can use putImageData() Method copies the image data back to the canvas.

example:

The following code obtains the color/alpha information of the first pixel in the returned ImageData object:

red=imgData.data[0];
green=imgData.data[1];
blue=imgData.data[2];
alpha=imgData.data[3];

Tip: you can also use the getImageData() method to reverse the color of each pixel of an image on the canvas.

Use this formula to traverse all pixels and change their color values:

red=255-old_red;
green=255-old_green;
blue=255-old_blue;

JavaScript syntax

var imgData=context.getImageData(x,y,width,height);

Parameter value

parameterdescribe
xThe x coordinate of the upper left corner where the copy starts.
yThe y coordinate of the upper left corner where the copy starts.
widthThe width of the rectangular area to be copied.
heightThe height of the rectangular area to be copied.
putImageData()

Put the image data (from the specified ImageData object) back on the canvas

Definition and Usage

The putImageData() method puts the image data (from the specified ImageData object) back on the canvas.

Tip: see getImageData() Method, which copies the pixel data of the specified rectangle on the canvas.

Tip: see createImageData() Method, which creates a new blank ImageData object.

JavaScript syntax:

context.putImageData(imgData,x,y,dirtyX,dirtyY,dirtyWidth,dirtyHeight);

Parameter value

parameterdescribe
imgDataSpecifies the ImageData object to put back on the canvas.
xThe x coordinate of the upper left corner of the ImageData object, in pixels.
yThe y coordinate of the upper left corner of the ImageData object, in pixels.
dirtyXOptional. Horizontal value (x), in pixels, where the image is placed on the canvas.
dirtyYOptional. Horizontal value (y), in pixels, where the image is placed on the canvas.
dirtyWidthOptional. The width used to draw the image on the canvas.
dirtyHeightOptional. The height used to draw the image on the canvas.

synthesis

attributedescribe
globalAlpha

Sets or returns the current alpha or transparent value of the plot

Definition and Usage

The globalAlpha property sets or returns the current transparency value (alpha or transparency) of the drawing.

The globalAlpha attribute value must be a number between 0.0 (fully transparent) and 1.0 (opaque).

Default:1.0
JavaScript syntax:context.globalAlpha=number;

Attribute value

valuedescribe
numberTransparent value. Must be between 0.0 (fully transparent) and 1.0 (opaque).
globalCompositeOperation

Sets or returns how a new image is drawn onto an existing image

Definition and Usage

The globalCompositeOperation property sets or returns how to draw a source (New) image onto a target (existing) image.

Source image = the drawing you intend to place on the canvas.

Target image = the drawing you have placed on the canvas.

Default:source-over
JavaScript syntax:context.globalCompositeOperation="source-in";

Attribute value

valuedescribe
source-over

Default. Displays the source image on the target image.

 

source-atop

Displays the source image at the top of the target image. The part of the source image outside the target image is invisible.

source-in

Displays the source image in the target image. Only the source image part in the target image will be displayed, and the target image is transparent.

 

source-out

Displays the source image outside the target image. Only the external image part of the target image will be displayed, and the target image is transparent.

 

destination-over

Displays the target image above the source image.

 

destination-atop

Displays the target image at the top of the source image. The target image part other than the source image will not be displayed.

destination-in

Displays the target image in the source image. Only the target image part in the source image will be displayed, and the source image is transparent.

 

destination-out

Displays the target image outside the source image. Only the target image outside the source image will be displayed, and the source image is transparent.

 

lighter

Display source image + target image.

 

copy

Displays the source image. Ignore the target image.

xor

Use the XOR operation to combine the source image with the target image.

 

 

other

methoddescribe
save()Saves the state of the current environment
restore()Returns previously saved path States and properties
createEvent()
getContext()
toDataURL()

Added by lala on Mon, 17 Jan 2022 18:46:14 +0200