Raphael :: Image Clip

Create an image CLIP

by klodoma

HTML

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenMax.min.js"></script>
<button id="clip-do">Clip Create</button>
<button id="clip-remove">Clip Remove</button>
<button id="transform">Transform</button>
<button id="reset">Reset</button>
<button id="animate">Animate</button>
<div id="the_canvas"></div>

CSS

body {
  padding: 10px;
  background-color: #eee;
}

#the_canvas {
  background-color: white;
  width: 550px;
  height: 550px;
}

JavaScript

// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) {
      return typeof args[number] != 'undefined' ? args[number] : match;
    });
  };
}

/**
 * Creates a RaphaelJS clip-rect item
 * @param {Object} item RaphaelJs Object
 */
function createRectClip(item, paper) {
  var box = item.getBBox();
  var rect = {
    x: box.x,
    y: box.y,
    width: box.width,
    height: box.height
  };

  item.attr({
    'clip-rect': "{0},{1},{2},{3}".format(rect.x, rect.y, rect.width, rect.height)
  });

  //create a temprect to see where the clip is
  var tmpRect = paper.rect(rect.x, rect.y, rect.width, rect.height);
  //item.clip.setAttribute("transform", tmpRect.node.getAttribute("transform"));
  //item.clip.setAttribute("clipPathUnits", "objectBoundingBox");
  item.clip.setAttribute("id", "myClipRect");
  //tmpRect.remove();

  return image.clip;
}

var canvas = document.getElementById("the_canvas");
var c = {
  width: canvas.offsetWidth,
  height: canvas.offsetHeight,
  center: {
    x: canvas.offsetWidth / 2,
    y: canvas.offsetHeight / 2
  }
};

// Creates Raphael canvas on canvas element
var paper = Raphael(canvas, c.width, c.height);

var image = paper.image("http://imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-300mmf_35-56g_ed_vr/img/sample/img_04.jpg", 10, 10, 300, 200);
image.attr({
  id: "myImage"
});

$("#clip-do").click(function() {
  var clip = createRectClip(image, paper);
  clip.setAttribute('width', 150);
});

$("#clip-remove").click(function() {
  image.attr({
    'clip-rect': null
  });
  if ($("#tmpRect")) {
    $("#tmpRect").remove();
  }
});

$("#transform").click(function() {
  image.transform("t100,100r45t100,0");
});

$("#reset").click(function() {
  image.transform("");
});
$("#animate").click(function() {
	$("#clip-remove").click();
  $("#clip-do").click();
  var myClipRect =...