我有一个伙伴帮助我(感谢 Yadid!)。
/*
this function returns the HTML of an object (same as object.html() - but with the wrapping element too)
*/
$.fn.outerHTML = function(){
// IE, Chrome & Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning
return (!this.length) ? this : (this[0].outerHTML || (
function(el){
var div = document.createElement('div');
div.appendChild(el.cloneNode(true));
var contents = div.innerHTML;
div = null;
return contents;
})(this[0]));
}
function saveEverything(){
var html = $('.canvas').outerHTML();
alert(html);
//Save "html" somewhere
}
$(window).load(function () {
var globalElement_width;
var globalElement_height;
$(document).ready(function () {
/*
the problem was that you were trying to get the size of the image before the image was actually loaded
- which returns wrong dimensions (the image is not there yet, so javascript can't get the width/height of the photo)
to solve it, we first need to initialize the image tag before we do anything -
we can do that by loading a blank image to it - "about:blank" (a 'blank' URL)
then bind to the img tag's "load" event - this event is fired after the photo is loaded and fully rendered
- once you get this event, you can read the dimension of the image
then,after we bind to the event, we can load the actual photo.
we do that by changing the "src" attribute of the <img> tag to the URL of the image you want to load
*/
$img = $('.canvas img').bind("load",function(){
globalElement_width = $img.width();
globalElement_height = $img.height();
$(".slider").slider({
step: 0.01, /* Changed from 0 to 100, to 0 to 1, with 1% steps (ie 0.01) . this will make the calculations easier */
min: 0,
max: 1,
value: 1,
slide: function (event, ui) {
resize_img(ui.value);
}
});
//now that we have the right dimension, we can center the image
center_img();
$('.canvas img').draggable();
});
$img.attr("src","http://media-cache-ec4.pinimg.com/736x/42/07/08/420708fc70c76f89c07bc93d13e6c479.jpg");
});
function center_img(){
//get the size of the canvas, substract the size of the image then divide by 2 which center it
var c = $('.canvas');
var l = (c.width() - c.find('img').width())/2;
var t = (c.height() - c.find('img').height())/2;
c.find('img').css({position:"absolute", top:t, left:l});
}
// the val will be anywhere between 0 to 1, so we just need to multiply that number with the original size of the image
function resize_img(val) {
// we get size of container so image wont be smaller than container
var w = $('.canvas').width();
// then use Math.min and Math.max, which return the minimum and maximum between 2 numbers
$('.canvas img').stop(true).animate({
width: Math.max(w, globalElement_width * Math.min(1,val))
},1, function(){
center_img();
});
}
}); //]]>