画布 - 剪辑多个图像

Canvas - clipping multiple images

本文关键字:图像 画布      更新时间:2023-09-26

我想将一堆图像剪辑成六边形。我让它工作了,但剪辑是跨所有十六进制的,而不是每个图像剪辑到只有一个十六进制。 我做错了什么?

这是一个现场演示:http://codepen.io/tev/pen/iJaHB

这是有问题的 js:

function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise, img, imgX, imgY) {
  if (sides < 3) return;
  var a = (Math.PI * 2)/sides;
  a = anticlockwise?-a:a;
  ctx.save();
  ctx.translate(x,y);
  ctx.rotate(startAngle);
  ctx.moveTo(radius,0);
  for (var i = 1; i < sides; i++) {
    ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
  }
  ctx.closePath();
  // add stroke
  ctx.lineWidth = 5;
  ctx.strokeStyle = '#056e96';
  ctx.stroke();
  // add stroke
  ctx.lineWidth = 4;
  ctx.strokeStyle = '#47b6c8';
  ctx.stroke();
  // add stroke
  ctx.lineWidth = 2;
  ctx.strokeStyle = '#056e96';
  ctx.stroke();
  // Clip to the current path
  ctx.clip();
  ctx.drawImage(img, imgX, imgY);
  ctx.restore();
}
// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
// Create an image element
var img = document.createElement('IMG');
var img2 = document.createElement('IMG');
// When the image is loaded, draw it
img.onload = function () {
  polygon(ctx, 120,120,100,6, 0,0,img, -120,-170);
}
img2.onload = function () {
  polygon(ctx, 280,212,100,6, 0,0,img2, -150,-120);
}
// Specify the src to load the image
img.src = "http://farm8.staticflickr.com/7381/9601443923_051d985646_n.jpg";
img2.src = "http://farm6.staticflickr.com/5496/9585303170_d005d2aaa9_n.jpg";
您需要

将其添加到polygon()方法中:

ctx.beginPath();

在此处查看修改后的笔

function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise, img, ...
    if (sides < 3) return;
    var a = (Math.PI * 2)/sides;
    a = anticlockwise?-a:a;
    ctx.save();
    ctx.translate(x,y);
    ctx.rotate(startAngle);
    ctx.beginPath();      /// for example here, before moveTo/lineTo
    ctx.moveTo(radius,0);
    ...

否则,线将累积,因此第二次调用多边形时,前一个多边形仍然存在。这就是为什么你也会在第一个六边形内看到部分图像的原因。