Canvas Manipulating Images

Last Updated:

How to Manipulate an Image

Actual Image

Apple

Canvas Image

To manipulate an image, follow these steps

  1. canvas - Assigning the canvas element to a variable.
  2. ctx - Assigning the 2d rendering context to another variable by calling the getContext('2d') method.
  3. img - Assigning a blank DOM object for a HTML img element by using the Image class to a variable.
  4. src - Setting the src attribute to the path of a valid image file, you load that image into the image object just as if you set the src attribute of an actual HTML img element.
  5. drawImage() - Use drawImage() canvas method to provide different ways to draw an image onto the canvas.
  6. font - Use font canvas property to specify the current text style to use when drawing text.
  7. fillStyle - Use fillStyle canvas property to specify the color to use inside shapes (any shape).
  8. fillText() - Use fillText() canvas method to draw a text string at the specified coordinates, filling the string's characters with the current fillStyle.

Example

HTML Online Editor
<!DOCTYPE html> <html lang="en-US"> <body> <p>Actual Image</p> <img src="apple.png"> <p>Canvas Image</p> <canvas id="point" width="100" height="100"> </canvas> <script> window.onload = function() { var canvas = document.getElementById("point"); var ctx = canvas.getContext("2d"); var img = new Image(); img.src = 'apple.png'; img.onload = function() { ctx.drawImage(img, 0, 0); ctx.font = "20px Arial"; ctx.fillStyle = "#999999"; ctx.fillText("Apple", 20, 60); } }; </script> </body> </html>

Syntax

ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

Attributes Value

ValueTypeExplanation
image Required Specifies an element to draw into the context.
sx Optional Specifies the x-axis coordinate of the top left corner of the sub-rectangle of the source image to draw into the destination context.
sy Optional Specifies the y-axis coordinate of the top left corner of the sub-rectangle of the source image to draw into the destination context.
sWidth Optional Specifies the width of the sub-rectangle of the source image to draw into the destination context.
sHeight Optional Specifies the height of the sub-rectangle of the source image to draw into the destination context.
dx Required Specifies the x-axis coordinate in the destination canvas at which to place the top-left corner of the source image.
dy Required Specifies the y-axis coordinate in the destination canvas at which to place the top-left corner of the source image.
dWidth Optional Specifies the width to draw the image in the destination canvas.
dHeight Optional Specifies the height to draw the image in the destination canvas.

Share this Page

Meet the Author