Image cropping example

concept:

 

When we draw the image using Canvas, we often want to retain only part of the image, then we can use the built-in image cropping Canvas API functions to implement this idea. This feature means that, in the canvas using the path, the path drawn only in a region including an image, the image is not drawn out of the path.

Using the context object image clip no arguments to realize an image cropping function of the Canvas element.

Now, let's apply some, in the application, after the completion of the drawing canvas background, call creat5StartClip function in a function, to create a five-pointed star of the path, and then use the clip method to set the crop area. Specific execution flow image is first loaded, and then calls the function drawImg, create a path creat5StarClip call this function, the crop area is provided, then after rendering image cropped

- The final image can be drawn within a range of a five-pointed star!

 

application:

Core code

function draw(id){
var canvas=document.getElementById("id");
if(canvas==null)
return false;
var context=canvas.getContext("2d");
var gr = context.createLinearGradient(0,400,300,0);
gr.addColorStop(0,'rgb(255,255,0)');
gr.addColorStop(1,'rgb(0,255,255)');
contxt.fillStyle = gr;
contxt.fillRect(0,0,400,300);
image=new Image();
image.onload = function(){
drawImg(context,img);
};
image.src = "image/Tulips.jpg";

}
function drawImg(context,image){
creat5StarClip(context);
context.drawImage(image,-50,-150,300,300);
}
function creat5StarClip(context){
var n = 0;
var dx = 100;
var dy = 0;
var s = 150;
context.beginPath();
context.translate(100,150);
var x = Math.sin(0);
var x = Math.cos(0);
var dig = Math.Pi/5*4;
for(var i = 0;i<5;i++)
{
var x = Math.sin(i*dig);
var x = Math.cos(i*dig);
comtext.lineTo(dx+x*s,dy+y*s);
}
context.clip();
}

Guess you like

Origin www.cnblogs.com/yanyanstyle/p/11348937.html