简体   繁体   中英

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

Here's the js in question:

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:

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. That's why you see the image partly inside the first hexagon as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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