Page 1 of 1

drawImage seems to break script

Posted: Wed Apr 07, 2010 5:14 am
by kalthar
Hey guys

I've got an image reflection javascript function that uses drawImage to flip the image, however it breaks the entire script

Code: Select all

$.fn.reflectme = function() {
  
  options = $.extend({
		height: 1/3,
		opacity: 0.5
	});
  
  var img = $(this);
  
  var imageWidth = img.width(), imageHeight = img.height(), reflection, reflectionHeight, wrapper, context, gradient;
  var reflectionHeight = Math.floor((options.height > 1) ? Math.min(imageHeight, options.height) : imageHeight * options.height);

  if ($.browser.msie) {
  	  var reflection = $("<img />").attr("src", $(this).attr('src')).css({
  		width: imageWidth,
  		height: imageHeight,
  		marginBottom: reflectionHeight - imageHeight,
  		filter: "flipv progid:DXImageTransform.Microsoft.Alpha(opacity=" + (options.opacity * 100) + ", style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy=" + (reflectionHeight / imageHeight * 100) + ")"
  	})[0];
  } else {
  	var reflection = $("<canvas />")[0];
  	if (!reflection.getContext) return;
  	  var context = reflection.getContext("2d");
  	try {
  		$(reflection).attr({width: imageWidth, height: reflectionHeight});
  		context.save();
  		context.translate(0, imageHeight-1);
  		context.scale(1, -1);
  		context.drawImage(img.attr('src'), 0, 0, imageWidth, imageHeight);
  		context.restore();
  		context.globalCompositeOperation = "destination-out";

  		gradient = context.createLinearGradient(0, 0, 0, reflectionHeight);
  		gradient.addColorStop(0, "rgba(255, 255, 255, " + (1 - options.opacity) + ")");
  		gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
  		context.fillStyle = gradient;
  		context.rect(0, 0, imageWidth, reflectionHeight);
  		context.fill();
  	} catch(e) {
  		return;
  	}
  }
  img.parent().append(reflection);

}
If I take that line out, the script works, but obviously I have no reflection.

Any help would be greatly appreciated.

Thanks guys.

Re: drawImage seems to break script

Posted: Wed Apr 07, 2010 11:54 am
by kaszu
Are you sure image has finished loading before you called drawImage ?