📜  图像的画布剪切路径 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:01:42.262000             🧑  作者: Mango

代码示例1
// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw,ch;
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;

// set some canvas styles
ctx.strokeStyle='black';

// an array to hold user's click-points that define the clipping area
var points=[];

// load the image 
var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/houses1.jpg";
function start(){

  // resize canvas to fit the img
  cw=canvas.width=img.width;
  ch=canvas.height=img.height;

  // draw the image at 25% opacity
  drawImage(0.25);

  // listen for mousedown and button clicks
  $('#canvas').mousedown(function(e){handleMouseDown(e);});
  $('#reset').click(function(){ points.length=0; drawImage(0.25); });
}



function handleMouseDown(e){

  // tell the browser that we're handling this event
  e.preventDefault();
  e.stopPropagation();

  // calculate mouseX & mouseY
  mx=parseInt(e.clientX-offsetX);
  my=parseInt(e.clientY-offsetY);

  // push the clicked point to the points[] array
  points.push({x:mx,y:my});

  // show the user an outline of their current clipping path
  outlineIt();

  // if the user clicked back in the original circle
  // then complete the clip
  if(points.length>1){
    var dx=mx-points[0].x;
    var dy=my-points[0].y;
    if(dx*dx+dy*dy<10*10){
      clipIt();
    }
  }
}


// redraw the image at the specified opacity
function drawImage(alpha){
  ctx.clearRect(0,0,cw,ch);
  ctx.globalAlpha=alpha;
  ctx.drawImage(img,0,0);
  ctx.globalAlpha=1.00;
}

// show the current potential clipping path
function outlineIt(){
  drawImage(0.25);
  ctx.beginPath();
  ctx.moveTo(points[0].x,points[0].y);
  for(var i=0;imaxX){maxX=p.x;}
    if(p.y>maxY){maxY=p.y;}
  }
  var width=maxX-minX;
  var height=maxY-minY;

  // clip the image into the user's clipping area
  ctx.save();
  ctx.clearRect(0,0,cw,ch);
  ctx.beginPath();
  ctx.moveTo(points[0].x,points[0].y);
  for(var i=1;i