I have added a javascript function in Wordpress. Here is the code for this function:
/*
* CraftMap
* author: Marcin Dziewulski
* web: http://www.jscraft.net
* email: info#jscraft.net
* license: http://www.jscraft.net/licensing.html
*/
(function($) {
$.fn.craftmap = function(options) {
var D = {
cookies: false,
fullscreen: false,
container: {
name: 'imgContent'
},
image: {
width: 1475,
height: 1200,
name: 'imgMap'
},
map: {
position: 'center'
},
marker: {
name: 'marker',
center: true,
popup: true,
popup_name: 'popup',
onClick: function(marker, popup){},
onClose: function(marker, popup){}
},
controls: {
init: true,
name: 'controls',
onClick: function(marker){}
},
preloader: {
init: true,
name: 'preloader',
onLoad: function(img, dimensions){}
}
}; // default settings
var S = $.extend(true, D, options);
return this.each(function(){
alert("?");
var M = $(this),
IMG = M.find('.'+S.image.name),
P = {
init: function(){
this._container.init();
if (S.fullscreen) {
this.fullscreen.init();
this.fullscreen.resize();
}
this._globals.init();
if (S.preloader.init) this.preloader.init();
this.map.init();
this.marker.init();
if (S.controls.init) this.controls.init();
},
_container: {
init: function(){
P._container.css();
P._container.wrap();
},
css: function(){
var max = {
width: '100%',
height: '100%'
};
IMG.css(max);
var css = {
position: 'relative',
overflow: 'hidden',
cursor: 'move'
}
M.css(css);
},
wrap: function(){
var css = {
zIndex: '1',
position: 'absolute',
width: S.image.width,
height: S.image.height
}
M.wrapInner($('<div />').addClass(S.container.name).css(css));
}
},
_globals: {
init: function(){
C = M.find('.'+S.container.name),
MARKER = C.find('.'+S.marker.name),
md = false, mx = 0, my = 0, ex = 0, ey = 0, delta = 0, mv = [], interval = 0,
D = {
w: M.width(),
h: M.height()
},
I = {
w: C.width(),
h: C.height()
}
if (S.controls.init){
CONTROLS = $('.'+S.controls.name).find('a');
}
}
},
_mouse: {
get: function(e){
var x = e.pageX,
y = e.pageY;
return {'x': x, 'y': y}
},
update: function(e){
var mouse = P._mouse.get(e),
x = mouse.x,
y = mouse.y,
movex = x-mx,
movey = y-my,
top = ey+movey,
left = ex+movex,
check = P.map.position.check(left, top),
css = {
top: check.y,
left: check.x
}
C.css(css);
if (S.cookies){
P.cookies.create('position', check.x + ',' + check.y, 7);
}
},
decelerate: function(e){
var l = mv.length, timer = 0;
if (l){
var tc = 20;
interval = setInterval(function(){
var position = C.position(), left = position.left, top = position.top,
remain = (tc-timer)/tc,
last = l-1,
xd = (mv[last].x-mv[0].x)/l,
yd = (mv[last].y-mv[0].y)/l,
vx = xd*remain,
vy = yd*remain,
coords = P.map.position.check(vx+left, vy+top),
css = {
left: coords.x,
top: coords.y
};
C.css(css);
++timer;
if (timer == tc){
clearInterval(interval);
timer = 0;
}
}, 40);
}
},
wheel: {
init: function(e){
M.handle = function(e){
e.preventDefault();
if (!e) {
e = window.event;
}
if (e.wheelDelta) {
delta = e.wheelDelta/120;
if (window.opera) {
delta = -delta;
}
} else if (e.detail) {
delta = -e.detail/3;
}
}
if (window.addEventListener){
window.addEventListener('DOMMouseScroll', M.handle, false);
}
window.onmousewheel = document.onmousewheel = M.handle;
},
remove: function(){
if (window.removeEventListener){
window.removeEventListener('DOMMouseScroll', M.handle, false);
}
window.onmousewheel = document.onmousewheel = null;
}
}
},
fullscreen: {
init: function(){
var win = $(window), w = win.width(), h = win.height(),
css = {
width: w,
height: h
}
M.css(css);
},
resize: function(){
$(window).resize(function(){
P.fullscreen.init();
D = {
w: M.width(),
h: M.height()
}
});
}
},
cookies: {
create: function(name, value, days) {
if (days) {
var date = new Date(), set = date.getTime() + (days * 24 * 60 * 60 * 1000);
date.setTime(set);
var expires = '; expires=' + date.toGMTString();
} else {
var expires = '';
}
document.cookie = name+'='+value+expires+'; path=/';
},
erase: function(name) {
cookies.create(name, '', -1);
},
read: function(name) {
var e = name + '=',
ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0) == ' '){
c = c.substring(1, c.length);
}
if (c.indexOf(e) == 0){
return c.substring(e.length,c.length);
}
}
return null;
}
},
preloader: {
init: function(){
var img = new Image(),
src = IMG.attr('src');
P.preloader.create();
$(img).addClass(S.image.name).attr('src', src).load(function(){
var t = $(this),
css = {
width: this.width,
height: this.height
}
t.css(css);
IMG.remove();
P.preloader.remove();
S.preloader.onLoad.call(this, t, css);
}).appendTo(C);
},
create: function(){
var css = {
position: 'absolute',
zIndex: '10',
top: '0',
left: '0',
width: '100%',
height: '100%'
}
M.append($('<div />').addClass(S.preloader.name).css(css));
},
remove: function(){
M.find('.'+S.preloader.name).fadeOut(400, function(){
var t = $(this);
t.remove();
});
}
},
map: {
init: function(){
P.map.position.set();
P.map.move();
},
position: {
set: function(){
if (S.cookies){
if (typeof P.cookies.read('position') != 'null') {
var position = P.cookies.read('position').split(','),
x = position[0],
y = position[1];
} else {
var x = (D.w-I.w)/2,
y = (D.h-I.h)/2;
}
} else {
var position = S.map.position;
switch (position){
case 'center':
var x = (D.w-I.w)/2,
y = (D.h-I.h)/2;
break;
case 'top_left':
var x = 0,
y = 0;
break;
case 'top_right':
var x = D.w-I.w,
y = 0;
break;
case 'bottom_left':
var x = 0,
y = D.h-I.h;
break;
case 'bottom_right':
var x = D.w-I.w,
y = D.h-I.h;
break;
default:
var coords = position.split(' '),
x = -(coords[0]),
y = -(coords[1]),
coords = P.map.position.check(x, y),
x = coords.x,
y = coords.y;
}
}
var css = { top: y, left: x }
C.css(css);
},
check: function(x, y){
if (y < (D.h-I.h)){
y = D.h-I.h;
} else if (y > 0){
y = 0;
}
if (x < (D.w-I.w)){
x = D.w-I.w;
} else if (x>0){
x = 0;
}
return {'x': x, 'y': y}
}
},
move: function(){
C.bind({
mousedown: function(e){
md = true;
var mouse = P._mouse.get(e);
mx = mouse.x,
my = mouse.y;
var el = C.position();
ex = el.left,
ey = el.top;
mv = [];
clearInterval(interval);
P._mouse.update(e);
return false;
},
mousemove: function(e){
if (md) {
P._mouse.update(e);
var mouse = P._mouse.get(e),
coords = {
x: mouse.x,
y: mouse.y
}
mv.push(coords);
if (mv.length > 15){
mv.pop();
}
}
return false;
},
mouseup: function(e){
if (md) md = false;
P._mouse.decelerate(e);
return false;
},
mouseout: function(){
if (md) md = false;
P._mouse.wheel.remove();
return false;
},
mouseover: function(e){
P._mouse.wheel.init(e);
return false;
},
mousewheel: function(e){
P._zoom.init(e);
}
});
}
},
_zoom: {
init: function(e){}
},
marker: {
init: function(){
P.marker.set();
P.marker.open();
P.marker.close();
},
set: function(){
MARKER.each(function(){
var t = $(this), position = t.attr('data-coords').split(',');
x = parseInt(position[0]), y = parseInt(position[1]),
css = {
position: 'absolute',
zIndex: '2',
top: y,
left: x
}
t.css(css);
}).wrapInner($('<div />').addClass(S.marker.name+'Content').hide());
},
open: function(){
MARKER.live('click', function(){
var t = $(this), id = t.attr('id'), marker = S.marker, w = t.width(), h = t.height(),
position = t.position(), x = position.left, y = position.top, id = t.attr('id'),
html = t.find('.'+marker.name+'Content').html();
if (marker.center){
var cy = -y+D.h/2-h/2,
cx = -x+D.w/2-w/2,
c = P.map.position.check(cx, cy),
animate = {
top: c.y,
left: c.x
};
C.animate(animate);
}
if (marker.popup){
$('.'+marker.popup_name).remove();
var css = {
position:'absolute',
zIndex:'3'
}
t.after(
$('<div />').addClass(marker.popup_name+' '+id).css(css).html(html).append(
$('<a />').addClass('close')
)
);
var POPUP = t.next('.'+marker.popup_name),
pw = POPUP.innerWidth(),
ph = POPUP.innerHeight(),
x0 = 0, y0 = 0;
if (x-pw < 0){
x0 = x;
} else if (x+pw/2 > I.w){
x0 = x-pw+w;
} else {
x0 = x-(pw/2-w/2);
}
if (y-ph < 0){
y0 = y+h+h/1.5;
} else {
y0 = y-ph-h/1.5;
}
if (x-pw < 0 && y-ph < 0){
x0 = x+w*2;
y0 = y-h/2;
} else if (y-ph < 0 && x+pw/2 > I.w){
x0 = x-pw-w/2;
y0 = y-h/2;
} else if (y+ph > I.h && x+pw/2 > I.w){
x0 = x-pw+w;
y0 = y-ph-h/2;
} else if (y+ph > I.h && x-pw < 0){
x0 = x;
y0 = y-ph-h/2;
}
var css = {
left: x0,
top: y0
}
POPUP.css(css);
}
P.controls.active.set(id);
marker.onClick.call(this, t, POPUP);
return false;
});
},
close: function(){
C.find('.close').live('click', function(){
var t = $(this), popup = t.parents('.'+S.marker.popup_name), marker = popup.prev('.'+S.marker.name);
popup.remove();
P.controls.active.remove();
S.marker.onClose.call(this, marker, popup);
return false;
});
}
},
controls: {
init: function(){
P.controls.set();
},
set: function(){
CONTROLS.click(function(){
var t = $(this), rel = t.attr('rel');
div = C.find('.'+ S.marker.name).filter('#'+rel);
div.trigger('click');
S.controls.onClick.call(this, div);
return false;
});
},
active: {
set: function(id){
if (S.controls.init){
CONTROLS.removeClass('active').filter(function(){
return this.rel == id;
}).addClass('active');
}
},
remove: function(){
if (S.controls.init) {
CONTROLS.removeClass('active');
}
}
}
}
}
P.init();
});
};
}(jQuery));
The problem is that the return in never called. How can I fix this problem? I have seen that this script works with jQuery version 1.7 or 1.8. So I told wordpress to load jquery 1.8.
I've created a new js file and I'm loading it using wordpress's function: wp_enqueue_script. So everything should work fine.
The return function is never called. What should I do/change in order to make it work.
Related
I am trying to make a quadratic curved arrow tool.
I was used demo in the following link for creating the tool.
http://kpomservices.com/oldweb/HTML5_Canvas_Curved_Lines.php
i was success to create an tool as I needs.
but I am getting some issues with that.
Hope someone here can help me on that issues...
here is the code I am using for creating the tool ..
line_number++;
var line;
var reinit_stroke = "";
fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center';
function _getQBezierValue(t, p1, p2, p3) {
var iT = 1 - t;
return iT * iT * p1 + 2 * iT * t * p2 + t * t * p3;
}
function getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, position) {
return {
x: _getQBezierValue(position, startX, cpX, endX),
y: _getQBezierValue(position, startY, cpY, endY)
};
}
canvas.on({
'object:selected': onObjectSelected,
'object:moving': onObjectMoving,
'before:selection:cleared': onBeforeSelectionCleared
});
(function drawQuadratic() {
line = new fabric.Path('M 65 0 Q 100, 100, 200, 0', { fill: '', selectable: false,hasBorders: false,hasControls: false,stroke: #000});
line.path[0][1] = posx;
line.path[0][2] = posy;
line.path[1][1] = posx+50;
line.path[1][2] = posy+50;
line.path[1][3] = posx+100;
line.path[1][4] = posy+100;
line.id = line_number;
//line.selectable = false;
canvas.add(line);
canvas.sendBackwards(line);
var pt = getQuadraticCurvePoint(line.path[0][1], line.path[0][2], line.path[1][1], line.path[1][2], line.path[1][3], line.path[1][4], 0.5);
var p1 = makeCurvePoint(pt.x, pt.y, null, line, null)
p1.name = "p1";
p1.id = line_number;
canvas.add(p1);
var p0 = makeCurveCircle(posx, posy, line, p1, null);
p0.name = "p0";
p0.id = line_number;
canvas.add(p0);
var p2 = makeArrow(posx+100, posy+100, null, p1, line);
p2.name = "p2";
p2.id = line_number;
canvas.add(p2);
var dx = line.path[1][3] - posx;
var dy = line.path[1][4] - posy;
var angle = Math.atan2(dy, dx) * 180 / Math.PI;
p2.setAngle(angle + 90);
p2.setCoords();
canvas.bringToFront(p2);
canvas.bringToFront(p0);
canvas.bringToFront(p1);
line.p2 = p2;
})();
function makeArrow(left, top, line1, line2, line3) {
var c = new fabric.Triangle({
width: 5,
height: 5,
left: left+5,
top: top+5,
strokeWidth: 10,
fill: #000,
opacity: 1,
stroke: #000
});
c.hasBorders = c.hasControls = false;
c.angle = 90;
c.line1 = line1;
c.line2 = line2;
c.line3 = line3;
return c;
}
function makeCurveCircle(left, top, line1, line2, line3) {
var c = new fabric.Circle({
radius: 5,
left: left,
top: top,
strokeWidth: 10,
fill: #000,
stroke: #000
});
c.hasBorders = c.hasControls = false;
c.line1 = line1;
c.line2 = line2;
c.line3 = line3;
return c;
}
function makeCurvePoint(left, top, line1, line2, line3) {
var c = new fabric.Circle({
radius: 5,
left: left,
top: top,
strokeWidth: 10,
fill: #000,
opacity: 0,
stroke: #000
});
c.hasBorders = c.hasControls = false;
c.angle = 90;
c.line1 = line1;
c.line2 = line2;
c.line3 = line3;
return c;
}
var prevselobj;
function onObjectSelected(e) {
var activeObject = e.target;
reinit_stroke = activeObject.stroke;
if (activeObject.name == "p0" || activeObject.name == "p2") {
if (prevselobj) {
prevselobj.line2.animate('opacity', '0', {
duration: 200,
onChange: canvas.renderAll.bind(canvas),
});
prevselobj.line2.selectable = false;
}
activeObject.line2.animate('opacity', '1', {
duration: 200,
onChange: canvas.renderAll.bind(canvas),
});
activeObject.line2.selectable = true;
prevselobj = activeObject;
}
}
function onBeforeSelectionCleared(e) {
var activeObject = e.target;
if (activeObject.name == "p0" || activeObject.name == "p2") {
activeObject.line2.animate('opacity', '0', {
duration: 200,
onChange: canvas.renderAll.bind(canvas),
});
activeObject.line2.selectable = false;
}
else if (activeObject.name == "p1") {
activeObject.animate('opacity', '0', {
duration: 200,
onChange: canvas.renderAll.bind(canvas),
});
activeObject.selectable = true;
}
}
function onObjectMoving(e) {
if (e.target.name == "p0" || e.target.name == "p2") {
var p = e.target;
var curvedline;
if (p.line1) {
p.line1.path[0][1] = p.left;
p.line1.path[0][2] = p.top + p.height/2;
curvedline = p.line1;
} else if (p.line3) {
p.line3.path[1][3] = p.left;
if(p.line3.path[0][2] <= p.line3.path[1][4])
p.line3.path[1][4] = p.top - p.height/2;
if(p.line3.path[0][2] > p.line3.path[1][4])
p.line3.path[1][4] = p.top + p.height/2;
p.line3.setCoords();
curvedline = p.line3;
}
if (curvedline) {
curvedline.setCoords();
var pt = getQuadraticCurvePoint(curvedline.path[0][1], curvedline.path[0][2], curvedline.path[1][1], curvedline.path[1][2], curvedline.path[1][3], curvedline.path[1][4], 0.5);
p.line2.left = pt.x;
p.line2.top = pt.y;
if (curvedline.p2) {
var pt = getQuadraticCurvePoint(curvedline.path[0][1], curvedline.path[0][2], curvedline.path[1][1], curvedline.path[1][2], curvedline.path[1][3], curvedline.path[1][4], 0.99);
curvedline.p2.left = pt.x;
curvedline.p2.top = pt.y;
var dx = curvedline.path[1][3] - pt.x;
var dy = curvedline.path[1][4] - pt.y;
var angle = Math.atan2(dy, dx) * 180 / Math.PI;
curvedline.p2.setAngle(angle + 90);
curvedline.p2.setCoords();
}
p.line2.setCoords();
}
if (e.target.text) {
e.target.text.left = p.left;
e.target.text.top = p.top;
e.target.text.setCoords();
}
} else if (e.target.name == "p1") {
var p = e.target;
if (p.line2) {
p.line2.path[1][1] = p.left;
p.line2.path[1][2] = p.top;
}
curvedline = p.line2;
if (curvedline) {
var pt = getQuadraticCurvePoint(curvedline.path[0][1], curvedline.path[0][2], curvedline.path[1][1], curvedline.path[1][2], curvedline.path[1][3], curvedline.path[1][4], 0.5);
p.left = pt.x;
p.top = pt.y;
p.setCoords();
}
if (curvedline) {
var pt = getQuadraticCurvePoint(curvedline.path[0][1], curvedline.path[0][2], curvedline.path[1][1], curvedline.path[1][2], curvedline.path[1][3], curvedline.path[1][4], 0.99);
curvedline.p2.left = pt.x;
curvedline.p2.top = pt.y;
var dx = curvedline.path[1][3] - pt.x;
var dy = curvedline.path[1][4] - pt.y;
var angle = Math.atan2(dy, dx) * 180 / Math.PI;
curvedline.p2.setAngle(angle + 90);
curvedline.p2.setCoords();
}
} else if (e.target.name == "p0" || e.target.name == "p2") {
var p = e.target;
p.line1 && p.line1.set({
'x2': p.left,
'y2': p.top
});
p.line2 && p.line2.set({
'x1': p.left,
'y1': p.top
});
p.line3 && p.line3.set({
'x1': p.left,
'y1': p.top
});
p.line4 && p.line4.set({
'x1': p.left,
'y1': p.top
});
}
p && reinit();
}
function reinit() {
canvas.remove(line);
line = new fabric.Path(line.path, { fill: '',selectable: false });
line.id = line_number;
line.stroke = reinit_stroke;
canvas.add(line);
canvas.sendBackwards(line);
}
canvas.on('mouse:over', function(e) {
if(e.target.type == "path")
{
canvas.sendBackwards(e.target);
}
});
I am using following code for delete the tool.
(Note: this code runs when I click on the delete button.
Delete button deletes the object selected. )
here is the code...
var objs = canvas.getObjects();
if (activeObject) {
active_id = activeObject.get('id');
canvas.forEachObject(function (obj) {
if(obj.get('id') == active_id)
{
if(obj.type == 'path')
{
obj.selectable = true;
canvas.remove(obj);
}
canvas.remove(obj);
}
});
canvas.remove(activeObject);
}
the issue I am getting is after delete this, If I create one other curved arrow in the designer(i.e. without reload the page) and move the nodes then its still showing the old path object which we already deleted.
and If I delete the newly created curved arrow then it removes all path from canvas, In short all Path object behave like one(Hope this is understandable) .
so, the path object is not getting deleted properly it is just getting hidden when I am deleting it. Or may be it is deleted but created again when I am moving another path object..
and if we save the canvas as json then we can see the path objects which are deleted too.
What I need to do is to delete the path object properly and save just the Path object currently showing on the canvas with nodes.
Please tell me if there is some solution for this issues..
Thanks..
I found the solution for the delete curve Issue.
We need to change the code at the reinit() functions.
It was overwrite the line_id to all the line(or say path) in the canvas.
Here is the code to replace with reinit() function..
function reinit() {
var objs = canvas.getObjects();
current_line = canvas.getActiveObject();
canvas.forEachObject(function (obj) {
if(obj.type == 'path' && obj.get("id") == current_line.get("id"))
{
canvas.remove(obj);
line = new fabric.Path(obj.path, { fill: '',selectable: false });
line.id = current_line.get("id");
line.stroke = reinit_stroke;
canvas.add(line);
canvas.sendBackwards(line);
}
});
}
Hope this can be helpful for someone who need this kind of solution..
Hi I am trying to create a Javascript function that would crop an image to 200x300. Here's my code which is not working:
var image = new SimpleImage ("image");
function crop (image, width, height){
width = 200;
height = 300;
if (image.width > 1){image.width = 200};
if (image.width > 1){image.height = 300};
return image;
}
print (crop(image, width, height));
You can use jQuery :
$(document).ready(function () {
$('#sample_input').awesomeCropper(
{ width: 150, height: 150, debug: true }
);
});
// Generated by CoffeeScript 1.6.3
(function() {
var $;
$ = jQuery;
$.awesomeCropper = function(inputAttachTo, options) {
var $applyButton, $cancelButton, $container, $cropSandbox, $fileSelect, $imagesContainer, $inputAttachTo, $progressBar, $resultIm, $sourceIm, $urlSelect, $urlSelectButton, a, cleanImages, div, drawImage, fileAllowed, handleDragOver, handleDropFileSelect, handleFileSelect, image, input, log, readFile, removeAreaSelect, removeLoading, saveCrop, setAreaSelect, setImages, setLoading, setOriginalSize, settings;
settings = {
width: 100,
height: 100,
debug: false
};
settings = $.extend(settings, options);
log = function() {
if (settings.debug) {
return typeof console !== "undefined" && console !== null ? console.log(arguments) : void 0;
}
};
$inputAttachTo = $(inputAttachTo);
input = function(type) {
return $("<input type = \"" + type + "\" />");
};
div = function() {
return $("<div/>");
};
a = function(text) {
return $("" + text + "");
};
image = function() {
return $('<img/>');
};
$container = div().insertAfter($inputAttachTo).addClass('awesome-cropper');
$cropSandbox = $('<canvas></canvas>');
$cropSandbox.attr({
width: settings.width,
height: settings.height
});
$container.append($cropSandbox);
$fileSelect = input('file');
$container.append($fileSelect);
if (settings.proxy_path !== void 0) {
$urlSelect = input('text');
$urlSelectButton = input('button');
$urlSelectButton.val('Upload from url');
$container.append(div().addClass('form-group').append($urlSelect).append($urlSelectButton));
}
$progressBar = div().addClass('progress hide').append(div().addClass('progress-bar').attr({
role: 'progressbar',
'aria-valuenow': "60",
'aria-valuemin': "0",
'aria-valuemax': "100",
style: "width: 60%;"
}));
$container.append($progressBar);
$resultIm = image();
$container.append($resultIm);
$sourceIm = image();
$applyButton = a('Apply').addClass('btn yes btn-primary');
$cancelButton = a('Cancel').addClass('btn btn-danger').attr({
'data-dismiss': "modal"
});
$imagesContainer = div().append(div().addClass('modal-dialog').append(div().addClass('modal-content').append(div().addClass('modal-body').append(div().addClass('col-md-9').append($sourceIm)).append(div().addClass('col-md-3').append($cropSandbox)).append(div().addClass('clearfix')), div().addClass('modal-footer').append(div().addClass('btn-group').append($cancelButton).append($applyButton))))).addClass('modal').attr({
role: 'dialog'
});
$container.append($imagesContainer);
removeAreaSelect = function(image) {
return image.imgAreaSelect({
remove: true
});
};
cleanImages = function() {
var im;
removeAreaSelect($sourceIm);
im = $sourceIm;
$sourceIm = image();
return im.replaceWith($sourceIm);
};
setLoading = function() {
return $progressBar.removeClass('hide');
};
removeLoading = function() {
$imagesContainer.on('shown.bs.modal', function() {
return setAreaSelect($sourceIm);
}).on('hidden.bs.modal', function() {
return cleanImages();
}).modal();
return $progressBar.addClass('hide');
};
setOriginalSize = function(img) {
var tempImage;
tempImage = new Image();
tempImage.onload = function() {
return img.attr({
'data-original-width': tempImage.width,
'data-original-height': tempImage.height
});
};
return tempImage.src = img.attr('src');
};
setImages = function(uri) {
return $sourceIm.attr('src', uri).load(function() {
removeLoading();
return setOriginalSize($sourceIm);
});
};
drawImage = function(img, x, y, width, height) {
var context, destHeight, destWidth, destX, destY, oHeight, oWidth, r, sourceHeight, sourceWidth, sourceX, sourceY;
oWidth = img.attr('data-original-width');
oHeight = img.attr('data-original-height');
if (oWidth > oHeight) {
r = oHeight / img.height();
} else {
r = oWidth / img.width();
}
sourceX = Math.round(x * r);
sourceY = Math.round(y * r);
sourceWidth = Math.round(width * r);
sourceHeight = Math.round(height * r);
destX = 0;
destY = 0;
destWidth = settings.width;
destHeight = settings.height;
context = $cropSandbox.get(0).getContext('2d');
return context.drawImage(img.get(0), sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
};
setAreaSelect = function(image) {
var viewPort, x2, y2,
_this = this;
viewPort = $(window).height() - 150;
if ($sourceIm.height() > viewPort) {
$sourceIm.css({
height: viewPort + "px"
});
}
log(image.width(), image.height());
if (image.width() / settings.width >= image.height() / settings.height) {
y2 = image.height();
x2 = Math.round(settings.width * (image.height() / settings.height));
} else {
x2 = image.width();
y2 = Math.round(settings.height * (image.width() / settings.width));
}
log(x2, y2, image.width(), image.height());
drawImage($sourceIm, 0, 0, x2 - 1, y2 - 1);
return image.imgAreaSelect({
aspectRatio: "" + settings.width + ":" + settings.height,
handles: true,
x1: 0,
y1: 0,
x2: x2,
y2: y2,
onSelectEnd: function(img, selection) {
return drawImage($sourceIm, selection.x1, selection.y1, selection.width - 1, selection.height - 1);
}
});
};
fileAllowed = function(name) {
var res;
res = name.match(/\.(jpg|png|gif|jpeg)$/mi);
if (!res) {
alert('Only *.jpeg, *.jpg, *.png, *.gif files allowed');
return false;
} else {
return true;
}
};
readFile = function(file) {
var reader;
reader = new FileReader();
setLoading();
reader.onload = function(e) {
return setImages(e.target.result);
};
return reader.readAsDataURL(file);
};
handleDropFileSelect = function(evt) {
evt.stopPropagation();
evt.preventDefault();
if (evt.originalEvent.dataTransfer.files[0] !== void 0) {
if (!fileAllowed(evt.originalEvent.dataTransfer.files[0].name)) {
return;
}
return readFile(evt.originalEvent.dataTransfer.files[0]);
}
};
handleDragOver = function(e) {
e.originalEvent.dataTransfer.dropEffect = "copy";
e.stopPropagation();
return e.preventDefault();
};
handleFileSelect = function(evt) {
if (evt.target.files[0] !== void 0) {
if (!fileAllowed(evt.target.files[0].name)) {
return;
}
readFile(evt.target.files[0]);
return evt.target.value = "";
}
};
saveCrop = function() {
var result;
result = $cropSandbox.get(0).toDataURL();
$resultIm.attr('src', result);
$inputAttachTo.val(result);
return cleanImages();
};
$fileSelect.on('change', handleFileSelect);
$container.on('dragover', handleDragOver);
$container.on('drop', handleDropFileSelect);
if (settings.proxy_path !== void 0) {
$urlSelect.on('dragover', handleDragOver);
$urlSelect.on('drop', handleDropFileSelect);
$urlSelectButton.click(function() {
var url;
if (!$urlSelect.val().match(/^(https?:\/\/)?/)) {
return;
}
if (!fileAllowed($urlSelect.val())) {
return;
}
setLoading();
url = settings.proxy_path.replace(/:url/, $urlSelect.val());
return $.get(url).done(function(data) {
return setImages(data);
}).fail(function(jqXNR, textStatus) {
$progressBar.addClass('hide');
return alert("Failed to load image");
});
});
}
$cancelButton.on('click', function() {
return cleanImages();
});
return $applyButton.on('click', function() {
saveCrop();
return $imagesContainer.modal('hide');
});
};
/*
# jQuery Awesome Cropper plugin
#
# Copyright 2013 8xx8, vdv73rus
#
# v0.0.2
*/
$.fn.extend({
awesomeCropper: function(options) {
return this.each(function() {
if ($(this).data("awesomeCropper")) {
if (options.remove) {
$(this).data("awesomeCropper").remove();
$(this).removeData("awesomeCropper");
} else {
$(this).data("awesomeCropper").setOptions(options);
}
} else if (!options.remove) {
$(this).data("awesomeCropper", new $.awesomeCropper(this, options));
}
if (options.instance) {
return $(this).data("awesomeCropper");
}
return this;
});
}
});
}).call(this);
Here is my code for this prompt (Duke Learn to Program classes). This worked when running in Duke's custom environment.
var image = new SimpleImage("duke_blue_devil.png");
var image2 = new SimpleImage(200, 300);
function crop() {
for (var pix of image.values()) {
var wid = image2.getWidth();
var ht = image2.getHeight();
if (pix.getX() < wid && pix.getY() < ht) {
image2.setPixel(pix.getX(), pix.getY(), pix);
} else;
}
}
crop(image);
print(image2);
print(image2.getWidth());
print(image2.getHeight());
I am developing a view for some items in my web site. Currently I have the items displayed in the HTML but now I need to draw some lines between the elements that will represent a connection between them, it's like a Gantt Chart but it doesn't include any time functionality, I only need to connect the items with the ones associated to them. I'm using JSTL to bring some data from a controller and I managed to draw the elements like the following image: http://i271.photobucket.com/albums/jj131/djrickel/before.png
And the way I need to display is in the following image:
http://i271.photobucket.com/albums/jj131/djrickel/after.png
This is how I'm creating my table containing the elements that I want to display:
<div class="container">
<table>
<tbody>
<c:forEach items="${nodeGraphs}" var="nodeGraph">
<tr>
<c:forEach var="i" begin="0" end="5">
<td>
<c:if test="${nodeGraph.columnID == i}">
<label class="label label-default">${nodeGraph.nodeObject.item.type}${nodeGraph.nodeObject.item.contextId}</label>
</c:if>
</td>
</c:forEach>
</tr>
</c:forEach>
</tbody>
</table>
</div>
Does anyone know a way to create connecting lines between the elements using JQuery, JSon, Javascript or any HTML process? I can change from the table I'm using to div or span without any issue. I'm just looking the best way to display the information. Thanks in advance.
Probably the best way to do that is use HTML5 canvas, but if You want use div's try use this code:
(On JSFiddle: http://fiddle.jshell.net/22rar61n/9/)
var Line = (function() {
var diff = function(a, b) {
var d = Math.abs(a - b);
if (d === 0) {
d = 1;
}
return d;
}
var countWidth = function(line) {
return diff(line.endX, line.startX);
};
var countHeight = function(line) {
return diff(line.endY, line.startY);
};
var Line = function(options) {
this.startX = options.startX;
this.startY = options.startY;
this.endX = options.endX;
this.endY = options.endY;
}
Line.prototype.drowIn = function($container) {
var self = this;
var line = jQuery("<div></div>", {
class: "line " + self.LineType(),
css: {
"color": "red",
"top": self.startY,
"left": self.startX,
"width": countWidth(self),
"height": countHeight(self),
"background-color": "#000"
}
});
$container.append(line);
};
Line.prototype.LineType = function() {
if (this.startX != this.endX) {
return "horizontal";
}
return "vertical";
}
return Line;
})();
var Arrow = (function() {
var Arrow = function(start, end) {
this.start = start;
this.end = end;
}
Arrow.prototype.drowIn = function($container) {
var ArrowContainer = jQuery("<div></div>", {
class: "arrowContainer"
});
var line1 = new Line({
startX: this.start.x,
startY: this.start.y,
endX: this.start.x,
endY: this.end.y
});
line1.drowIn(ArrowContainer);
var line2 = new Line({
startX: this.start.x,
startY: this.end.y,
endX: this.end.x,
endY: this.end.y
});
line2.drowIn(ArrowContainer);
$container.append(ArrowContainer);
}
return Arrow;
})();
var Element = (function() {
var Element = function(options) {
var op = jQuery.extend({}, options);
this.x = op.x || -1;
this.y = op.y || -1;
this.content = op.content || "";
this.container = op.$container || "";
this.node = null;
this.subElements = [];
};
Element.prototype.addSubElement = function(element) {
element.container = this.container;
element.content = this.content + "." + (this.subElements.length + 1);
this.subElements.push(element);
};
Element.prototype.drow = function() {
var self = this;
this.node = jQuery("<div></div>", {
class: "element",
text: this.content,
css: {
top: self.y,
left: self.x
}
});
this.container.append(this.node);
var nexLvl = 0;
var lastHeight = nexLvl;
var lastLvl = 0;
var oldIndex = -1;
var outerHeightAndTop = jQuery(self.node).outerHeight() + jQuery(self.node).offset().top;
jQuery.each(this.subElements, function(index, element) {
var height = outerHeightAndTop * (index + 1 + lastLvl);
if (lastHeight != 0) {
height = lastHeight + outerHeightAndTop;
}
if (nexLvl != 0) {
oldIndex = index;
height = height + ((jQuery(self.node).outerHeight()) * nexLvl);
lastLvl = nexLvl;
}
lastHeight = height;
nexLvl = element.getMaxLevel();
element.x = jQuery(self.node).outerWidth() + jQuery(self.node).offset().left;
element.y = height;
element.drow();
self.connectWith(element);
});
};
Element.prototype.connectWith = function(element) {
var startY = jQuery(this.node).outerHeight() + this.y;
var startX = (jQuery(this.node).outerWidth() / 2) + this.x;
var endY = (jQuery(element.node).outerHeight() / 2) + element.y;
var arrow = new Arrow({
x: startX,
y: startY
}, {
x: element.x,
y: endY
});
arrow.drowIn(this.container);
};
function getLevelOnPosition(index) {
return this.subElements[index].getMaxLevel();
}
Element.prototype.getMaxLevel = function(initLvl) {
var lvl = initLvl || 0;
var maxLvl = lvl;
if (this.subElements.length > 0) {
maxLvl = lvl++;
}
jQuery.each(this.subElements, function(index, element) {
lvl = element.getMaxLevel(lvl);
if (lvl > maxLvl) {
maxLvl = lvl;
}
});
return maxLvl;
}
return Element;
})();
jQuery(document).ready(function() {
var container = jQuery("#container");
var e = new Element({
x: 10,
y: 10,
content: "a1",
$container: container
});
var sube = new Element();
e.addSubElement(sube);
var sube2 = new Element();
sube.addSubElement(sube2);
sube2.addSubElement(new Element());
var e2 = new Element();
e.addSubElement(e2);
e2.addSubElement(new Element());
e.addSubElement(new Element());
e.drow();
});
#container {
position: relative;
}
#container > .element {
position: absolute;
border: 1px solid black;
background-color: gray;
color: white;
padding: 2px;
z-index: 10;
}
#container > .arrowContainer {
position: absolute;
}
#container > .arrowContainer > .line {
position: absolute;
z-index: 50;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container"></div>
I found this code on the internet. I pasted into my notepad++ and then changed these two files to match the ones that I created on my desktop.
<script src='C:/Users/home-1/Desktop/Box2dWeb-2.1.a.3.js'></script>
<script src='C:/Users/home-1/Desktop/example5.js'></script>
I have the script tag in the html file but I have tried it in the code and in the file and neither of them seem to work.
For some reason the page does not work. I would like to know what is different with this page and why it does not work.
Box2dWeb-2.1.a.3.js
and then created the example5.js file and have it also on my desktop. This should show a canvas along with several objects that you can drop and drag on the screen.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mouse Joint</title>
<script src='C:/Users/home-1/Desktop/Box2dWeb-2.1.a.3.js'></script>
<script src='C:/Users/home-1/Desktop/example5.js'></script>
<style>
canvas
{
background-color:black;
}
</style>
</head>
<body>
<canvas id='b2dCanvas' width='1024' height='500'>Broswer does not
support Canvas Tag</canvas>
<script>
(function() {
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2Body = Box2D.Dynamics.b2Body;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2World = Box2D.Dynamics.b2World;
var b2MassData = Box2D.Collision.Shapes.b2MassData;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var Physics = window.Physics = function(element,scale) {
var gravity = new b2Vec2(0,9.8);
this.world = new b2World(gravity, true);
this.element = element;
this.context = element.getContext("2d");
this.scale = scale || 20;
this.dtRemaining = 0;
this.stepAmount = 1/60;
};
Physics.prototype.debug = function() {
this.debugDraw = new b2DebugDraw();
this.debugDraw.SetSprite(this.context);
this.debugDraw.SetDrawScale(this.scale);
this.debugDraw.SetFillAlpha(0.3);
this.debugDraw.SetLineThickness(1.0);
this.debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
this.world.SetDebugDraw(this.debugDraw);
};
Physics.prototype.step = function(dt) {
this.dtRemaining += dt;
while(this.dtRemaining > this.stepAmount) {
this.dtRemaining -= this.stepAmount;
this.world.Step(this.stepAmount,
10, // velocity iterations
10);// position iterations
}
if(this.debugDraw) {
this.world.DrawDebugData();
} else {
var obj = this.world.GetBodyList();
this.context.clearRect(0,0,this.element.width,this.element.height);
this.context.save();
this.context.scale(this.scale,this.scale);
while(obj) {
var body = obj.GetUserData();
if(body)
{
body.draw(this.context);
}
obj = obj.GetNext();
}
this.context.restore();
}
};
Physics.prototype.click = function(callback) {
var self = this;
function handleClick(e) {
e.preventDefault();
var point = {
x: (e.offsetX || e.layerX) / self.scale,
y: (e.offsetY || e.layerY) / self.scale
};
self.world.QueryPoint(function(fixture) {
callback(fixture.GetBody(),
fixture,
point);
},point);
}
this.element.addEventListener("mousedown",handleClick);
this.element.addEventListener("touchstart",handleClick);
};
Physics.prototype.dragNDrop = function() {
var self = this;
var obj = null;
var joint = null;
function calculateWorldPosition(e) {
return point = {
x: (e.offsetX || e.layerX) / self.scale,
y: (e.offsetY || e.layerY) / self.scale
};
}
this.element.addEventListener("mousedown",function(e) {
e.preventDefault();
var point = calculateWorldPosition(e);
self.world.QueryPoint(function(fixture) {
obj = fixture.GetBody().GetUserData();
},point);
});
this.element.addEventListener("mousemove",function(e) {
if(!obj) { return; }
var point = calculateWorldPosition(e);
if(!joint) {
var jointDefinition = new Box2D.Dynamics.Joints.b2MouseJointDef();
jointDefinition.bodyA = self.world.GetGroundBody();
jointDefinition.bodyB = obj.body;
jointDefinition.target.Set(point.x,point.y);
jointDefinition.maxForce = 100000;
jointDefinition.timeStep = self.stepAmount;
joint = self.world.CreateJoint(jointDefinition);
}
joint.SetTarget(new b2Vec2(point.x,point.y));
});
this.element.addEventListener("mouseup",function(e) {
obj = null;
if(joint) {
self.world.DestroyJoint(joint);
joint = null;
}
});
};
Physics.prototype.collision = function() {
this.listener = new Box2D.Dynamics.b2ContactListener();
this.listener.PostSolve = function(contact,impulse) {
var bodyA = contact.GetFixtureA().GetBody().GetUserData(),
bodyB = contact.GetFixtureB().GetBody().GetUserData();
if(bodyA.contact) { bodyA.contact(contact,impulse,true) }
if(bodyB.contact) { bodyB.contact(contact,impulse,false) }
};
this.world.SetContactListener(this.listener);
};
var Body = window.Body = function(physics,details) {
this.details = details = details || {};
// Create the definition
this.definition = new b2BodyDef();
// Set up the definition
for(var k in this.definitionDefaults) {
this.definition[k] = details[k] || this.definitionDefaults[k];
}
this.definition.position = new b2Vec2(details.x || 0, details.y || 0);
this.definition.linearVelocity = new b2Vec2(details.vx || 0, details.vy || 0);
this.definition.userData = this;
this.definition.type = details.type == "static" ? b2Body.b2_staticBody :
b2Body.b2_dynamicBody;
// Create the Body
this.body = physics.world.CreateBody(this.definition);
// Create the fixture
this.fixtureDef = new b2FixtureDef();
for(var l in this.fixtureDefaults) {
this.fixtureDef[l] = details[l] || this.fixtureDefaults[l];
}
details.shape = details.shape || this.defaults.shape;
switch(details.shape) {
case "circle":
details.radius = details.radius || this.defaults.radius;
this.fixtureDef.shape = new b2CircleShape(details.radius);
break;
case "polygon":
this.fixtureDef.shape = new b2PolygonShape();
this.fixtureDef.shape.SetAsArray(details.points,details.points.length);
break;
case "block":
default:
details.width = details.width || this.defaults.width;
details.height = details.height || this.defaults.height;
this.fixtureDef.shape = new b2PolygonShape();
this.fixtureDef.shape.SetAsBox(details.width/2,
details.height/2);
break;
}
this.body.CreateFixture(this.fixtureDef);
};
Body.prototype.defaults = {
shape: "block",
width: 4,
height: 4,
radius: 1
};
Body.prototype.fixtureDefaults = {
density: 2,
friction: 1,
restitution: 0.2
};
Body.prototype.definitionDefaults = {
active: true,
allowSleep: true,
angle: 0,
angularVelocity: 0,
awake: true,
bullet: false,
fixedRotation: false
};
Body.prototype.draw = function(context) {
var pos = this.body.GetPosition(),
angle = this.body.GetAngle();
context.save();
context.translate(pos.x,pos.y);
context.rotate(angle);
if(this.details.color) {
context.fillStyle = this.details.color;
switch(this.details.shape) {
case "circle":
context.beginPath();
context.arc(0,0,this.details.radius,0,Math.PI*2);
context.fill();
break;
case "polygon":
var points = this.details.points;
context.beginPath();
context.moveTo(points[0].x,points[0].y);
for(var i=1;i<points.length;i++) {
context.lineTo(points[i].x,points[i].y);
}
context.fill();
break;
case "block":
context.fillRect(-this.details.width/2,
-this.details.height/2,
this.details.width,
this.details.height);
default:
break;
}
}
if(this.details.image) {
context.drawImage(this.details.image,
-this.details.width/2,
-this.details.height/2,
this.details.width,
this.details.height);
}
context.restore();
}
var physics,
lastFrame = new Date().getTime();
window.gameLoop = function() {
var tm = new Date().getTime();
requestAnimationFrame(gameLoop);
var dt = (tm - lastFrame) / 1000;
if(dt > 1/15) { dt = 1/15; }
physics.step(dt);
lastFrame = tm;
};
function init() {
var img = new Image();
// Wait for the image to load
img.addEventListener("load", function() {
physics = window.physics = new Physics(document.getElementById("b2dCanvas"));
physics.collision();
// Create some walls
new Body(physics, { color: "red", type: "static", x: 0, y: 0, height: 50, width: 0.5 });
new Body(physics, { color: "red", type: "static", x:51, y: 0, height: 50, width: 0.5});
new Body(physics, { color: "red", type: "static", x: 0, y: 0, height: 0.5, width: 120 });
new Body(physics, { color: "red", type: "static", x: 0, y:25, height: 0.5, width: 120 });
new Body(physics, { image: img, x: 5, y: 8 });
new Body(physics, { image: img, x: 13, y: 8 });
new Body(physics, { color: "blue", x: 8, y: 3 });
new Body(physics, { color: "gray", shape: "circle", radius: 4, x: 5, y: 20 });
new Body(physics, { color: "pink", shape: "polygon",
points: [ { x: 0, y: 0 }, { x: 0, y: 4 },{ x: -10, y: 0 } ],
x: 20, y: 5 });
physics.dragNDrop();
requestAnimationFrame(gameLoop);
});
img.src = "images/bricks.jpg";
}
window.addEventListener("load",init);
}());
// Lastly, add in the `requestAnimationFrame` shim, if necessary. Does nothing
// if `requestAnimationFrame` is already on the `window` object.
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
}());
</script>
</body>
</html>
Below is what the code is supposed to produce on the screen. I was wanting to use this one as an example but have not been able to get it to work.
This is how I have the files currently:
<script src='Box2dWeb-2.1.a.3.js'></script>
<script src='example5.js'></script>
You need a file:/// prefix for both of them, e.g. file:///C:\Users\home-1\Desktop\example5.js; I’d just use a relative path, though.
Assuming the file is on your desktop too,
<script src="Box2dWeb-2.1.a.3.js"></script>
<script src="example5.js"></script>
Much more portable.
I cannot get cloudzoom to work with my woocommerce site, every time I choose an attribute ie size the main image disappears, it is like cloudzoom is trying to force an attribute image. I am absolutely pants at javascript and looking through the file I cannot see where I need to edit or delete the code. Any help would be greatly appreciated, I don't need the atribute image function to work at all so just stripping out the code would suit me. Here is the code...
(function ($) {
$(document).ready(function () {
$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
});
function format(str) {
for (var i = 1; i < arguments.length; i++) {
str = str.replace('%' + (i - 1), arguments[i]);
}
return str;
}
function CloudZoom(jWin, opts) {
var sImg = $('img', jWin);
var img1;
var img2;
var zoomDiv = null;
var $mouseTrap = null;
var lens = null;
var $tint = null;
var softFocus = null;
var $ie6Fix = null;
var zoomImage;
var controlTimer = 0;
var cw, ch;
var destU = 0;
var destV = 0;
var currV = 0;
var currU = 0;
var filesLoaded = 0;
var mx,
my;
var ctx = this, zw;
// Display an image loading message. This message gets deleted when the images have loaded and the zoom init function is called.
// We add a small delay before the message is displayed to avoid the message flicking on then off again virtually immediately if the
// images load really fast, e.g. from the cache.
//var ctx = this;
setTimeout(function () {
// <img src="/images/loading.gif"/>
if ($mouseTrap === null) {
var w = jWin.width();
jWin.parent().append(format('<div style="width:%0px;position:absolute;top:75%;left:%1px;text-align:center" class="cloud-zoom-loading" >Loading...</div>', w / 3, (w / 2) - (w / 6))).find(':last').css('opacity', 0.5);
}
}, 200);
var ie6FixRemove = function () {
if ($ie6Fix !== null) {
$ie6Fix.remove();
$ie6Fix = null;
}
};
// Removes cursor, tint layer, blur layer etc.
this.removeBits = function () {
//$mouseTrap.unbind();
if (lens) {
lens.remove();
lens = null;
}
if ($tint) {
$tint.remove();
$tint = null;
}
if (softFocus) {
softFocus.remove();
softFocus = null;
}
ie6FixRemove();
$('.cloud-zoom-loading', jWin.parent()).remove();
};
this.destroy = function () {
jWin.data('zoom', null);
if ($mouseTrap) {
$mouseTrap.unbind();
$mouseTrap.remove();
$mouseTrap = null;
}
if (zoomDiv) {
zoomDiv.remove();
zoomDiv = null;
}
//ie6FixRemove();
this.removeBits();
// DON'T FORGET TO REMOVE JQUERY 'DATA' VALUES
};
// This is called when the zoom window has faded out so it can be removed.
this.fadedOut = function () {
if (zoomDiv) {
zoomDiv.remove();
zoomDiv = null;
}
this.removeBits();
//ie6FixRemove();
};
this.controlLoop = function () {
if (lens) {
var x = (mx - sImg.offset().left - (cw * 0.5)) >> 0;
var y = (my - sImg.offset().top - (ch * 0.5)) >> 0;
if (x < 0) {
x = 0;
}
else if (x > (sImg.outerWidth() - cw)) {
x = (sImg.outerWidth() - cw);
}
if (y < 0) {
y = 0;
}
else if (y > (sImg.outerHeight() - ch)) {
y = (sImg.outerHeight() - ch);
}
lens.css({
left: x,
top: y
});
lens.css('background-position', (-x) + 'px ' + (-y) + 'px');
destU = (((x) / sImg.outerWidth()) * zoomImage.width) >> 0;
destV = (((y) / sImg.outerHeight()) * zoomImage.height) >> 0;
currU += (destU - currU) / opts.smoothMove;
currV += (destV - currV) / opts.smoothMove;
zoomDiv.css('background-position', (-(currU >> 0) + 'px ') + (-(currV >> 0) + 'px'));
}
controlTimer = setTimeout(function () {
ctx.controlLoop();
}, 30);
};
this.init2 = function (img, id) {
filesLoaded++;
//console.log(img.src + ' ' + id + ' ' + img.width);
if (id === 1) {
zoomImage = img;
}
//this.images[id] = img;
if (filesLoaded === 2) {
this.init();
}
};
/* Init function start. */
this.init = function () {
// Remove loading message (if present);
$('.cloud-zoom-loading', jWin.parent()).remove();
/* Add a box (mouseTrap) over the small image to trap mouse events.
It has priority over zoom window to avoid issues with inner zoom.
We need the dummy background image as IE does not trap mouse events on
transparent parts of a div.
*/
$mouseTrap = jWin.parent().append(format("<div class='mousetrap' style='background-image:url(\".\");z-index:3;position:absolute;width:%0px;height:%1px;left:%2px;top:%3px;\'></div>", sImg.outerWidth(), sImg.outerHeight(), 0, 0)).find(':last');
//////////////////////////////////////////////////////////////////////
/* Do as little as possible in mousemove event to prevent slowdown. */
$mouseTrap.bind('mousemove', this, function (event) {
// Just update the mouse position
mx = event.pageX;
my = event.pageY;
});
//////////////////////////////////////////////////////////////////////
$mouseTrap.bind('mouseleave', this, function (event) {
clearTimeout(controlTimer);
//event.data.removeBits();
if(lens) { lens.fadeOut(299); }
if($tint) { $tint.fadeOut(299); }
if(softFocus) { softFocus.fadeOut(299); }
zoomDiv.fadeOut(300, function () {
ctx.fadedOut();
});
return false;
});
//////////////////////////////////////////////////////////////////////
$mouseTrap.bind('mouseenter', this, function (event) {
mx = event.pageX;
my = event.pageY;
zw = event.data;
if (zoomDiv) {
zoomDiv.stop(true, false);
zoomDiv.remove();
}
var xPos = opts.adjustX,
yPos = opts.adjustY;
var siw = sImg.outerWidth();
var sih = sImg.outerHeight();
var w = opts.zoomWidth;
var h = opts.zoomHeight;
if (opts.zoomWidth == 'auto') {
w = siw;
}
if (opts.zoomHeight == 'auto') {
h = sih;
}
//$('#info').text( xPos + ' ' + yPos + ' ' + siw + ' ' + sih );
var appendTo = jWin.parent(); // attach to the wrapper
switch (opts.position) {
case 'top':
yPos -= h; // + opts.adjustY;
break;
case 'right':
xPos += siw; // + opts.adjustX;
break;
case 'bottom':
yPos += sih; // + opts.adjustY;
break;
case 'left':
xPos -= w; // + opts.adjustX;
break;
case 'inside':
w = siw;
h = sih;
break;
// All other values, try and find an id in the dom to attach to.
default:
appendTo = $('#' + opts.position);
// If dom element doesn't exit, just use 'right' position as default.
if (!appendTo.length) {
appendTo = jWin;
xPos += siw; //+ opts.adjustX;
yPos += sih; // + opts.adjustY;
} else {
w = appendTo.innerWidth();
h = appendTo.innerHeight();
}
}
zoomDiv = appendTo.append(format('<div id="cloud-zoom-big" class="cloud-zoom-big" style="display:none;position:absolute;left:%0px;top:%1px;width:%2px;height:%3px;background-image:url(\'%4\');z-index:2;"></div>', xPos, yPos, w, h, zoomImage.src)).find(':last');
// Add the title from title tag.
if (sImg.attr('title') && opts.showTitle) {
zoomDiv.append(format('<div class="cloud-zoom-title">%0</div>', sImg.attr('title'))).find(':last').css('opacity', opts.titleOpacity);
}
// Fix ie6 select elements wrong z-index bug. Placing an iFrame over the select element solves the issue...
if ($.browser.msie && $.browser.version < 7) {
$ie6Fix = $('<iframe frameborder="0" src="#"></iframe>').css({
position: "absolute",
left: xPos,
top: yPos,
zIndex: 99,
width: w,
height: h
}).insertBefore(zoomDiv);
}
zoomDiv.fadeIn(500);
if (lens) {
lens.remove();
lens = null;
} /* Work out size of cursor */
cw = (sImg.outerWidth() / zoomImage.width) * zoomDiv.width();
ch = (sImg.outerHeight() / zoomImage.height) * zoomDiv.height();
// Attach mouse, initially invisible to prevent first frame glitch
lens = jWin.append(format("<div class = 'cloud-zoom-lens' style='display:none;z-index:1;position:absolute;width:%0px;height:%1px;opacity:0.4'></div>", cw, ch)).find(':last');
$mouseTrap.css('cursor', lens.css('cursor'));
var noTrans = false;
// Init tint layer if needed. (Not relevant if using inside mode)
if (opts.tint) {
/* lens.css('background', 'url("' + sImg.attr('src') + '")'); */
$tint = jWin.append(format('<div style="display:none;position:absolute; left:0px; top:0px; width:%0px; height:%1px; background-color:%2;" />', sImg.outerWidth(), sImg.outerHeight(), opts.tint)).find(':last');
$tint.css('opacity', opts.tintOpacity);
noTrans = true;
$tint.fadeIn(500);
}
if (opts.softFocus) {
lens.css('background', 'url("' + sImg.attr('src') + '")');
softFocus = jWin.append(format('<div style="position:absolute;display:none;top:2px; left:2px; width:%0px; height:%1px;" />', sImg.outerWidth() - 2, sImg.outerHeight() - 2, opts.tint)).find(':last');
softFocus.css('background', 'url("' + sImg.attr('src') + '")');
softFocus.css('opacity', 0.5);
noTrans = true;
softFocus.fadeIn(500);
}
if (!noTrans) {
lens.css('opacity', opts.lensOpacity);
}
if ( opts.position !== 'inside' ) { lens.fadeIn(500); }
// Start processing.
zw.controlLoop();
return; // Don't return false here otherwise opera will not detect change of the mouse pointer type.
});
};
img1 = new Image();
$(img1).load(function () {
ctx.init2(this, 0);
});
img1.src = sImg.attr('src');
img2 = new Image();
$(img2).load(function () {
ctx.init2(this, 1);
});
img2.src = jWin.attr('href');
}
$.fn.CloudZoom = function (options) {
// IE6 background image flicker fix
try {
document.execCommand("BackgroundImageCache", false, true);
} catch (e) {}
this.each(function () {
var relOpts, opts;
// Hmm...eval...slap on wrist.
eval('var a = {' + $(this).attr('rel') + '}');
relOpts = a;
if ($(this).is('.cloud-zoom')) {
$(this).css({
'position': 'relative',
'display': 'block'
});
$('img', $(this)).css({
'display': 'block'
});
// Wrap an outer div around the link so we can attach things without them becoming part of the link.
// But not if wrap already exists.
if ($(this).parent().attr('id') != 'wrap') {
$(this).wrap('<div id="wrap" style="top:0px;z-index:4;position:relative;"></div>');
}
opts = $.extend({}, $.fn.CloudZoom.defaults, options);
opts = $.extend({}, opts, relOpts);
$(this).data('zoom', new CloudZoom($(this), opts));
} else if ($(this).is('.cloud-zoom-gallery')) {
opts = $.extend({}, relOpts, options);
$(this).data('relOpts', opts);
$(this).bind('click', $(this), function (event) {
var data = event.data.data('relOpts');
// Destroy the previous zoom
$('#' + data.useZoom).data('zoom').destroy();
// Change the biglink to point to the new big image.
$('#' + data.useZoom).attr('href', event.data.attr('href'));
// Change the small image to point to the new small image.
$('#' + data.useZoom + ' img').attr('src', event.data.data('relOpts').smallImage);
// Init a new zoom with the new images.
$('#zoom-cb').attr('href', event.data.attr('href'));
$('#' + event.data.data('relOpts').useZoom).CloudZoom();
return false;
});
}
});
return this;
};
$.fn.CloudZoom.defaults = {
zoomWidth: 'auto',
zoomHeight: 'auto',
position: 'right',
tint: false,
tintOpacity: 0.5,
lensOpacity: 0.5,
softFocus: false,
smoothMove: 3,
showTitle: false,
titleOpacity: 0.5,
adjustX: 0,
adjustY: 0
};
})(jQuery);