简体   繁体   English

画布 - 剪裁多个图像

[英]Canvas - clipping multiple images

I want to clip a bunch of images into hexagon shapes. 我想将一堆图像剪成六边形。 I have it sort of working, but the clipping is across all the hexes instead of each image clipping to only one hex. 我有点工作,但裁剪是跨越所有的十六进制而不是每个图像裁剪到只有一个十六进制。 What am I doing wrong? 我究竟做错了什么?

Here's a live demo: http://codepen.io/tev/pen/iJaHB 这是一个现场演示: http//codepen.io/tev/pen/iJaHB

Here's the js in question: 这是有问题的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";

You need to add this to your polygon() method: 您需要将其添加到polygon()方法:

ctx.beginPath();

See modified pen here 在这里看到修改过的笔

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);
    ...

If not the lines will accumulate so the second time you call polygon the previous polygon will still exist. 如果不是行将累积,所以第二次调用polygon时,前一个多边形仍然存在。 That's why you see the image partly inside the first hexagon as well. 这就是为什么你看到图像部分位于第一个六边形内部的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM