HTML5 canvas provides drawing pictures on canvas, which can draw some parts of the image and increase or decrease the size of the image.

Drawing method

//Draw a picture in (x, y) of the canvas
context.drawImage(img, x, y);

//Draw a picture in (x, y) of the canvas and set the width and height
context.drawImage(img, x, y, width, height);

//Cut the image and draw the image in (x, y) of the canvas
context.drawImage(img, sx, sy, swidth, sheight, x, y, width, height);

/ / parameter
//img: Specifies the image, canvas, or video to use.
//sx: optional. The X coordinate position where the cut starts.
//sy: optional. The Y coordinate position of the start cut.
//swidth: optional. The width of the cut image.
//sheight: optional. The height of the cut image.
//x: place the X coordinate position of the image on the canvas.
//y: place the Y coordinate position of the image on the canvas.
//width: optional. The width of the image to use. (stretch or shrink image)
//height: optional. The height of the image to use. (stretch or shrink image)

For example:

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

var image = new Image();
image.src = "http://cdn.zdyla.com/upload/post/ca10ac99-8e02-4c9d-b112-c4a4c7264665.jpeg"
image.onload = function (){
    ctx.drawImage(image,20,20,160,160);
}


Zoom picture

Zoom is achieved by controlling the width and height of the drawn image.

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

var image = new Image();
image.src = "http://cdn.zdyla.com/upload/post/ca10ac99-8e02-4c9d-b112-c4a4c7264665.jpeg"
image.onload = function (){
    ctx.drawImage(image,50,50,100,100);
}


Crop picture

Draw the cutting position in the original image and then draw it on the canvas.

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

var image = new Image();
image.src = "http://cdn.zdyla.com/upload/post/ca10ac99-8e02-4c9d-b112-c4a4c7264665.jpeg"
image.onload = function (){
    ctx.drawImage(image,800,800,1500,1500,20,20,160,160);
}

All Comments

Leave a Reply Cancel Reply

Tips: Your email address will not be disclosed!

If you can't see clearly,please click to change...

Popular Posts

Collections