To start to draw text on a canvas, use the following properties and methods:
font
fillText(text,x,y)
strokeText(text,x,y)
The HTML canvas font property sets the current font properties for text content on the canvas. The HTML canvas fillText() method draws filled text on the canvas, and the HTML canvas strokeText() method draws text (no fill) on the canvas.
To fill text in color add fillStyle property, and to align the text add the textAlign property.
The HTML canvas textAlign property sets the current alignment for text content, according to the anchor point. The HTML canvas textAlign can have the following values: center/ end/ left/ right/ start(default).
The HTML canvas measureText() method returns an object that contains the width of the specified text (you can use this method if you need to know the width of a text, before writing it on the canvas.).
Example:
<!DOCTYPE html>
<html>
<body>
<canvas id="measureText" width="300" height="150" style="border:1px solid #333;"></canvas>
<script>
var c = document.getElementById("measureText");
var ctx = c.getContext("2d");
ctx.font = "25px Tahoma";
var txt = "Hello World"
ctx.fillText("width:" + ctx.measureText(txt).width, 10, 50);
ctx.fillText(txt, 10, 100);
</script>
</body>
</html>
The HTML canvas drawImage() method creates an image, canvas, or video onto the canvas.
Note: You cannot call the drawImage() method before the image has loaded. You can call drawImage() from window.onload() /or document.getElementById(“imageID”).onload.
Syntax (position the image on the canvas):
context.drawImage(img/v,x,y);
img/v – defines the image, canvas, or video element to use.
x – the x-coordinate where to place the image on the canvas.
y – the y-coordinate where to place the image on the canvas.
Example:
<!DOCTYPE html>
<html>
<body>
<p>Image to use:</p>
<img id="ghost" width="320" height="240" src="https://lenadesign.org/wp-content/uploads/2021/06/ghost-example.jpg" alt="Ghost">
<p>Canvas:</p>
<canvas id="ghostCanvas" width="340" height="260" style="border:1px solid #333;">
</canvas>
<script>
window.onload = function() {
var c = document.getElementById("ghostCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("ghost");
ctx.drawImage(img, 10, 10);
}
</script>
</body>
</html>
Output:
Syntax (clip the image and position the clipped part on the canvas):
The HTML canvas quadraticCurveTo() method adds a point to the current path by using the specified control points that represent a quadratic Bézier curve.
Syntax:
context.quadraticCurveTo(cpx,cpy,x,y);
cpx – the x-coordinate of the Bézier control point.
cpy – the y-coordinate of the Bézier control point.