Canvas Examples – Add Text | Add Image | Resize Image | Change Canvas Color

How to add text to Canvas?

For add text we can do that using fillText(‘text’, x, y) or strokeText(“text”, x, y) method. The text is rendered using the current stroke or fill style, which can be a color, gradient, or pattern. You can specify a number of text settings, such as the font family, size, and weight, and the text alignment and baseline.

 

The textBaseline attribute’s keywords which correspond to the alignment points in the font, where:

  • top corresponds to the top of the em square
  • hanging is the hanging baseline
  • middle is the middle of the em square
  • alphabetic is the alphabetic baseline
  • ideographic is the ideographic baseline
  • bottom corresponds to the bottom of the em square

 

Here is example for add text with gradient, font family, size, weight, shadow.

canvas = document.getElementById(‘myCanvas’);

context = canvas.getContext(‘2d’);

context.font=”italic 30px Georgia”;

context.strokeStyle = “rgba(237,229,0,1)”;

context.shadowOffsetX = 2;

context.shadowOffsetY = 2;

context.shadowBlur = 1;

context.shadowColor = “rgba(0,0,0,1)”;

var gradient = context.createLinearGradient(200,70,200,110);

gradient.addColorStop(0, “#f55b5b”);

gradient.addColorStop(1, “#3112a3”);

context.fillStyle = gradient;

context.fillText(“Hello World”, x, y);

 

How to add image to Canvas?

 

To draw an image using HTML5 Canvas, we can use the drawImage() method which requires an image object and a destination point. The destination point is relative to the top left corner of the image.

 

The drawImage function includes three parameters and is expressed in the form drawImage(object image, float x, float y). The image file formats supported within the canvas element and drawImage function are .jpg, .gif, and .png.

 

The drawImage() method requires an image object, we must first create an image and wait for it to load before instantiating drawImage(). We can do this by using the onload property of the image object.

 

Here is example for add image to Canvas.

canvas = document.getElementById(‘myCanvas’);

context = canvas.getContext(‘2d’);

var imgObj = new Image();

imgObj.onload = function() {

context.drawImage(imgObj, 10, 10);

}

imgObj.src = “image/nature.jpg”;

 

How to resize image?

Now we have drawImage() method for draw image on Canvas, for resize image we can use same method with optional height and width parameters and is expressed in the form drawImage(object image, float x, float y, [optional width], [optional height]).

 

Here is example for add and resize image to Canvas.

canvas = document.getElementById(‘myCanvas’);

context = canvas.getContext(‘2d’);

var imgObj = new Image();

imgObj.onload = function() {

context.drawImage(imgObj, 10, 10, 200, 100);

}

imgObj.src = “image/nature.jpg”;

 

 

Canvas Examples – Draw Line | Rectangle | Circle | Undo