Related
I'd like to elaborate on the accepted answer to this question.
I'm looking at improving the minimal shiny app below (extracted from the accepted answer) with the following features:
1) draw the rectangle + a text label. The label comes from R (input$foo), e.g., from a dropdown. To avoid the edge cases where the labels fall outside the images, labels should be placed inside their rectangles.
2) use a different color for the rectangles and their labels depending on the label
3) ability for the user to delete a rectangle by double-clicking inside it. In the case of multiple matches (overlap, nested), the rectangle with the smallest area should be deleted.
Brownie points for 1): the dropdown could appear next to the cursor like is done here (code here). If possible, the dropdown list should be passed from server.R and not be fixed/hardcoded. The reason is that depending on some user input, a different dropdown could be shown. E.g., we might have one dropdown for fruits c('banana','pineapple','grapefruit'), one dropdown for animals c('raccoon','dog','cat'), etc.
# JS and CSS modified from: https://stackoverflow.com/a/17409472/8099834
css <- "
#canvas {
width:2000px;
height:2000px;
border: 10px solid transparent;
}
.rectangle {
border: 5px solid #FFFF00;
position: absolute;
}
"
js <-
"function initDraw(canvas) {
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
function setMousePosition(e) {
var ev = e || window.event; //Moz || IE
if (ev.pageX) { //Moz
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) { //IE
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
};
var element = null;
canvas.onmousemove = function (e) {
setMousePosition(e);
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onclick = function (e) {
if (element !== null) {
var coord = {
left: element.style.left,
top: element.style.top,
width: element.style.width,
height: element.style.height
};
Shiny.onInputChange('rectCoord', coord);
element = null;
canvas.style.cursor = \"default\";
} else {
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle'
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element);
canvas.style.cursor = \"crosshair\";
}
}
};
$(document).on('shiny:sessioninitialized', function(event) {
initDraw(document.getElementById('canvas'));
});
"
library(shiny)
ui <- fluidPage(
tags$head(
tags$style(css),
tags$script(HTML(js))
),
fluidRow(
column(width = 6,
# inline is necessary
# ...otherwise we can draw rectangles over entire fluidRow
uiOutput("canvas", inline = TRUE)),
column(
width = 6,
verbatimTextOutput("rectCoordOutput")
)
)
)
server <- function(input, output, session) {
output$canvas <- renderUI({
tags$img(src = "https://www.r-project.org/logo/Rlogo.png")
})
output$rectCoordOutput <- renderPrint({
input$rectCoord
})
}
shinyApp(ui, server)
This solution uses kyamagu's bbox_annotator and is based on demo.html. I'm not familiar with JS, so it's not the prettiest. Limitations are:
Choosing a different image url will remove previous rectangles
I edited the JS a bit to change the rectangle/text color, so you won't be able to pull directly from the original repo
My changes probably broke input_method = "fixed" and "text", I only tested input_method = "select"
ui.R
# Adapted from https://github.com/kyamagu/bbox-annotator/
# Edited original JS to add color_list as an option
# ...should be the same length as labels
# ...and controls the color of the rectangle
# ...will probably be broken for input_method = "fixed" or "text"
# Also added color as a value in each rectangle entry
js <- '
$(document).ready(function() {
// define options to pass to bounding box constructor
var options = {
url: "https://www.r-project.org/logo/Rlogo.svg",
input_method: "select",
labels: [""],
color_list: [""],
onchange: function(entries) {
Shiny.onInputChange("rectCoord", JSON.stringify(entries, null, " "));
}
};
// Initialize the bounding-box annotator.
var annotator = new BBoxAnnotator(options);
// Initialize the reset button.
$("#reset_button").click(function(e) {
annotator.clear_all();
})
// define function to reset the bbox
// ...upon choosing new label category or new url
function reset_bbox(options) {
document.getElementById("bbox_annotator").setAttribute("style", "display:inline-block");
$(".image_frame").remove();
annotator = new BBoxAnnotator(options);
}
// update image url from shiny
Shiny.addCustomMessageHandler("change-img-url", function(url) {
options.url = url;
options.width = null;
options.height = null;
reset_bbox(options);
});
// update colors and categories from shiny
Shiny.addCustomMessageHandler("update-category-list", function(vals) {
options.labels = Object.values(vals);
options.color_list = Object.keys(vals);
reset_bbox(options);
});
// redraw rectangles based on list of entries
Shiny.addCustomMessageHandler("redraw-rects", function(vals) {
var arr = JSON.parse(vals);
arr.forEach(function(rect){
annotator.add_entry(rect);
});
if (annotator.onchange) {
annotator.onchange(annotator.entries);
}
});
});
'
ui <- fluidPage(
tags$head(tags$script(HTML(js)),
tags$head(
tags$script(src = "bbox_annotation.js")
)),
titlePanel("Bounding box annotator demo"),
sidebarLayout(
sidebarPanel(
selectInput(
"img_url",
"URLs",
c(
"https://www.r-project.org/logo/Rlogo.svg",
"https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png"
)
),
selectInput("category_type", "Label Category", c("animals", "fruits")),
div(HTML(
'<input id="reset_button" type="reset" />'
)),
HTML(
'<input id="annotation_data" name="annotation_data" type="hidden" />'
),
hr(),
h4("Entries"),
verbatimTextOutput("rectCoordOutput")
),
mainPanel(div(id = "bbox_annotator", style = "display:inline-block"))
)
)
server.R
server <- function(input, output, session) {
# user choices
output$rectCoordOutput <- renderPrint({
if(!is.null(input$rectCoord)) {
as.data.frame(jsonlite::fromJSON(input$rectCoord))
}
})
# send chosen URL from shiny to JS
observeEvent(input$img_url, {
session$sendCustomMessage("change-img-url", input$img_url)
})
# send chosen category list from shiny to JS
observeEvent(input$category_type, {
vals <- switch(input$category_type,
fruits = list("yellow" = "banana",
"orange" = "pineapple",
"pink" = "grapefruit"),
animals = list("grey" = "raccoon",
"brown" = "dog",
"tan" = "cat")
)
# update category list
session$sendCustomMessage("update-category-list", vals)
# redraw rectangles
session$sendCustomMessage("redraw-rects", input$rectCoord)
})
}
www/bbox_annotation.js
// Generated by CoffeeScript 2.5.0
(function() {
// https://github.com/kyamagu/bbox-annotator/blob/master/bbox_annotator.coffee
// Use coffee-script compiler to obtain a javascript file.
// coffee -c bbox_annotator.coffee
// See http://coffeescript.org/
// BBox selection window.
var BBoxSelector;
BBoxSelector = class BBoxSelector {
// Initializes selector in the image frame.
constructor(image_frame, options) {
if (options == null) {
options = {};
}
options.input_method || (options.input_method = "text");
this.image_frame = image_frame;
this.border_width = options.border_width || 2;
this.selector = $('<div class="bbox_selector"></div>');
this.selector.css({
// rectangle color when dragging
"border": this.border_width + "px dotted rgb(127,255,127)",
"position": "absolute"
});
this.image_frame.append(this.selector);
this.selector.css({
"border-width": this.border_width
});
this.selector.hide();
this.create_label_box(options);
}
// Initializes a label input box.
create_label_box(options) {
var i, label, len, ref;
options.labels || (options.labels = ["object"]);
this.label_box = $('<div class="label_box" style="z-index: 1000"></div>');
this.label_box.css({
"position": "absolute"
});
this.image_frame.append(this.label_box);
switch (options.input_method) {
case 'select':
if (typeof options.labels === "string") {
options.labels = [options.labels];
}
this.label_input = $('<select class="label_input" name="label"></select>');
this.label_box.append(this.label_input);
this.label_input.append($('<option value>choose an item</option>'));
ref = options.labels;
for (i = 0, len = ref.length; i < len; i++) {
label = ref[i];
this.label_input.append('<option value="' + label + '">' + label + '</option>');
}
this.label_input.change(function(e) {
return this.blur();
});
break;
case 'text':
if (typeof options.labels === "string") {
options.labels = [options.labels];
}
this.label_input = $('<input class="label_input" name="label" ' + 'type="text" value>');
this.label_box.append(this.label_input);
this.label_input.autocomplete({
source: options.labels || [''],
autoFocus: true
});
break;
case 'fixed':
if ($.isArray(options.labels)) {
options.labels = options.labels[0];
}
this.label_input = $('<input class="label_input" name="label" type="text">');
this.label_box.append(this.label_input);
this.label_input.val(options.labels);
break;
default:
throw 'Invalid label_input parameter: ' + options.input_method;
}
return this.label_box.hide();
}
// Crop x and y to the image size.
crop(pageX, pageY) {
var point;
return point = {
x: Math.min(Math.max(Math.round(pageX - this.image_frame.offset().left), 0), Math.round(this.image_frame.width() - 1)),
y: Math.min(Math.max(Math.round(pageY - this.image_frame.offset().top), 0), Math.round(this.image_frame.height() - 1))
};
}
// When a new selection is made.
start(pageX, pageY) {
this.pointer = this.crop(pageX, pageY);
this.offset = this.pointer;
this.refresh();
this.selector.show();
$('body').css('cursor', 'crosshair');
return document.onselectstart = function() {
return false;
};
}
// When a selection updates.
update_rectangle(pageX, pageY) {
this.pointer = this.crop(pageX, pageY);
return this.refresh();
}
// When starting to input label.
input_label(options) {
$('body').css('cursor', 'default');
document.onselectstart = function() {
return true;
};
this.label_box.show();
return this.label_input.focus();
}
// Finish and return the annotation.
finish(options) {
var data;
this.label_box.hide();
this.selector.hide();
data = this.rectangle();
data.label = $.trim(this.label_input.val().toLowerCase());
if (options.input_method !== 'fixed') {
this.label_input.val('');
}
return data;
}
// Get a rectangle.
rectangle() {
var rect, x1, x2, y1, y2;
x1 = Math.min(this.offset.x, this.pointer.x);
y1 = Math.min(this.offset.y, this.pointer.y);
x2 = Math.max(this.offset.x, this.pointer.x);
y2 = Math.max(this.offset.y, this.pointer.y);
return rect = {
left: x1,
top: y1,
width: x2 - x1 + 1,
height: y2 - y1 + 1
};
}
// Update css of the box.
refresh() {
var rect;
rect = this.rectangle();
this.selector.css({
left: (rect.left - this.border_width) + 'px',
top: (rect.top - this.border_width) + 'px',
width: rect.width + 'px',
height: rect.height + 'px'
});
return this.label_box.css({
left: (rect.left - this.border_width) + 'px',
top: (rect.top + rect.height + this.border_width) + 'px'
});
}
// Return input element.
get_input_element() {
return this.label_input;
}
};
// Annotator object definition.
this.BBoxAnnotator = class BBoxAnnotator {
// Initialize the annotator layout and events.
constructor(options) {
var annotator, image_element;
annotator = this;
this.annotator_element = $(options.id || "#bbox_annotator");
// allow us to access colors and labels in future steps
this.color_list = options.color_list;
this.label_list = options.labels;
this.border_width = options.border_width || 2;
this.show_label = options.show_label || (options.input_method !== "fixed");
if (options.multiple != null) {
this.multiple = options.multiple;
} else {
this.multiple = true;
}
this.image_frame = $('<div class="image_frame"></div>');
this.annotator_element.append(this.image_frame);
if (options.guide) {
annotator.initialize_guide(options.guide);
}
image_element = new Image();
image_element.src = options.url;
image_element.onload = function() {
options.width || (options.width = image_element.width);
options.height || (options.height = image_element.height);
annotator.annotator_element.css({
"width": (options.width + annotator.border_width) + 'px',
"height": (options.height + annotator.border_width) + 'px',
"padding-left": (annotator.border_width / 2) + 'px',
"padding-top": (annotator.border_width / 2) + 'px',
"cursor": "crosshair",
"overflow": "hidden"
});
annotator.image_frame.css({
"background-image": "url('" + image_element.src + "')",
"width": options.width + "px",
"height": options.height + "px",
"position": "relative"
});
annotator.selector = new BBoxSelector(annotator.image_frame, options);
return annotator.initialize_events(options);
};
image_element.onerror = function() {
return annotator.annotator_element.text("Invalid image URL: " + options.url);
};
this.entries = [];
this.onchange = options.onchange;
}
// Initialize events.
initialize_events(options) {
var annotator, selector, status;
status = 'free';
this.hit_menuitem = false;
annotator = this;
selector = annotator.selector;
this.annotator_element.mousedown(function(e) {
if (!annotator.hit_menuitem) {
switch (status) {
case 'free':
case 'input':
if (status === 'input') {
selector.get_input_element().blur();
}
if (e.which === 1) { // left button
selector.start(e.pageX, e.pageY);
status = 'hold';
}
}
}
annotator.hit_menuitem = false;
return true;
});
$(window).mousemove(function(e) {
var offset;
switch (status) {
case 'hold':
selector.update_rectangle(e.pageX, e.pageY);
}
if (annotator.guide_h) {
offset = annotator.image_frame.offset();
annotator.guide_h.css('top', Math.floor(e.pageY - offset.top) + 'px');
annotator.guide_v.css('left', Math.floor(e.pageX - offset.left) + 'px');
}
return true;
});
$(window).mouseup(function(e) {
switch (status) {
case 'hold':
selector.update_rectangle(e.pageX, e.pageY);
selector.input_label(options);
status = 'input';
if (options.input_method === 'fixed') {
selector.get_input_element().blur();
}
}
return true;
});
selector.get_input_element().blur(function(e) {
var data;
switch (status) {
case 'input':
data = selector.finish(options);
if (data.label) {
// store color with the entry
// ...so we can redraw the rectangle upon changing label category
data.color = annotator.color_list[annotator.label_list.indexOf(data.label)];
annotator.add_entry(data);
if (annotator.onchange) {
annotator.onchange(annotator.entries);
}
}
status = 'free';
}
return true;
});
selector.get_input_element().keypress(function(e) {
switch (status) {
case 'input':
if (e.which === 13) {
selector.get_input_element().blur();
}
}
return e.which !== 13;
});
selector.get_input_element().mousedown(function(e) {
return annotator.hit_menuitem = true;
});
selector.get_input_element().mousemove(function(e) {
return annotator.hit_menuitem = true;
});
selector.get_input_element().mouseup(function(e) {
return annotator.hit_menuitem = true;
});
return selector.get_input_element().parent().mousedown(function(e) {
return annotator.hit_menuitem = true;
});
}
// Add a new entry.
add_entry(entry) {
var annotator, box_element, close_button, text_box;
if (!this.multiple) {
this.annotator_element.find(".annotated_bounding_box").detach();
this.entries.splice(0);
}
this.entries.push(entry);
box_element = $('<div class="annotated_bounding_box"></div>');
box_element.appendTo(this.image_frame).css({
// rectangle color -- when stopped dragging
"border": this.border_width + "px solid " + entry.color,
"position": "absolute",
"top": (entry.top - this.border_width) + "px",
"left": (entry.left - this.border_width) + "px",
"width": entry.width + "px",
"height": entry.height + "px",
// text color when stopped dragging
"color": entry.color,
"font-family": "monospace",
"font-size": "small"
});
close_button = $('<div></div>').appendTo(box_element).css({
"position": "absolute",
"top": "-8px",
"right": "-8px",
"width": "16px",
"height": "0",
"padding": "16px 0 0 0",
"overflow": "hidden",
"color": "#fff",
"background-color": "#030",
"border": "2px solid #fff",
"-moz-border-radius": "18px",
"-webkit-border-radius": "18px",
"border-radius": "18px",
"cursor": "pointer",
"-moz-user-select": "none",
"-webkit-user-select": "none",
"user-select": "none",
"text-align": "center"
});
$("<div></div>").appendTo(close_button).html('×').css({
"display": "block",
"text-align": "center",
"width": "16px",
"position": "absolute",
"top": "-2px",
"left": "0",
"font-size": "16px",
"line-height": "16px",
"font-family": '"Helvetica Neue", Consolas, Verdana, Tahoma, Calibri, ' + 'Helvetica, Menlo, "Droid Sans", sans-serif'
});
text_box = $('<div></div>').appendTo(box_element).css({
"overflow": "hidden"
});
if (this.show_label) {
text_box.text(entry.label);
}
annotator = this;
box_element.hover((function(e) {
return close_button.show();
}), (function(e) {
return close_button.hide();
}));
close_button.mousedown(function(e) {
return annotator.hit_menuitem = true;
});
close_button.click(function(e) {
var clicked_box, index;
clicked_box = close_button.parent(".annotated_bounding_box");
index = clicked_box.prevAll(".annotated_bounding_box").length;
clicked_box.detach();
annotator.entries.splice(index, 1);
return annotator.onchange(annotator.entries);
});
return close_button.hide();
}
// Clear all entries.
clear_all(e) {
this.annotator_element.find(".annotated_bounding_box").detach();
this.entries.splice(0);
return this.onchange(this.entries);
}
// Add crosshair guide.
initialize_guide(options) {
this.guide_h = $('<div class="guide_h"></div>').appendTo(this.image_frame).css({
"border": "1px dotted " + (options.color || '#000'),
"height": "0",
"width": "100%",
"position": "absolute",
"top": "0",
"left": "0"
});
return this.guide_v = $('<div class="guide_v"></div>').appendTo(this.image_frame).css({
"border": "1px dotted " + (options.color || '#000'),
"height": "100%",
"width": "0",
"position": "absolute",
"top": "0",
"left": "0"
});
}
};
}).call(this);
Hy there! I plan to use Rater.js in my project and so far I am happy with the library. There is only one issue I can't resolve alone. Pls. take a look at
https://jsfiddle.net/herbert_hinterberger/r1cgnpt3/.
At the very bottom of the script, I defined step_size: 1.
(".rating").rate();
//or for example
var options = {
max_value: 5,
step_size: 1,
}
Now I would expect that when I hover over the stars, only full stars are selected. But still, half stars are selected too. Any Idea what I a doing wrong?
In your example code, you are calling $(".rating").rate(); without options (line number 499).
After commenting it, you will end-up with something like below
/*
* A highly customizable rating widget that supports images, utf8 glyphs and other html elements!
* https://github.com/auxiliary/rater
*/
; (function ($, window) {
$.fn.textWidth = function () {
var html_calc = $('<span>' + $(this).html() + '</span>');
html_calc.css('font-size', $(this).css('font-size')).hide();
html_calc.prependTo('body');
var width = html_calc.width();
html_calc.remove();
if (width == 0) {
var total = 0;
$(this).eq(0).children().each(function () {
total += $(this).textWidth();
});
return total;
}
return width;
};
$.fn.textHeight = function () {
var html_calc = $('<span>' + $(this).html() + '</span>');
html_calc.css('font-size', $(this).css('font-size')).hide();
html_calc.prependTo('body');
var height = html_calc.height();
html_calc.remove();
return height;
};
/*
* IE8 doesn't support isArray!
*/
Array.isArray = function (obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
/*
* Utf-32 isn't supported by default, so we have to use Utf-8 surrogates
*/
String.prototype.getCodePointLength = function () {
return this.length - this.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g).length + 1;
};
String.fromCodePoint = function () {
var chars = Array.prototype.slice.call(arguments);
for (var i = chars.length; i-- > 0;) {
var n = chars[i] - 0x10000;
if (n >= 0)
chars.splice(i, 1, 0xD800 + (n >> 10), 0xDC00 + (n & 0x3FF));
}
return String.fromCharCode.apply(null, chars);
};
/*
* Starting the plugin itself
*/
$.fn.rate = function (options) {
if (options === undefined || typeof options === 'object') {
return this.each(function () {
if (!$.data(this, "rate")) {
$.data(this, "rate", new Rate(this, options));
}
});
}
else if (typeof options === 'string') {
var args = arguments;
var returns;
this.each(function () {
var instance = $.data(this, "rate");
if (instance instanceof Rate && typeof instance[options] === 'function') {
returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
}
if (options === 'destroy') {
// Unbind all events and empty the plugin data from instance
$(instance.element).off();
$.data(this, 'rate', null);
}
});
return returns !== undefined ? returns : this;
}
};
function Rate(element, options) {
this.element = element;
this.settings = $.extend({}, $.fn.rate.settings, options);
this.set_faces = {}; // value, symbol pairs
this.build();
}
Rate.prototype.build = function () {
this.layers = {};
this.value = 0;
this.raise_select_layer = false;
if (this.settings.initial_value) {
this.value = this.settings.initial_value;
}
if ($(this.element).attr("data-rate-value")) {
this.value = $(this.element).attr("data-rate-value");
}
/*
* Calculate the selected width based on the initial value
*/
var selected_width = this.value / this.settings.max_value * 100;
/*
* Let's support single strings as symbols as well as objects
*/
if (typeof this.settings.symbols[this.settings.selected_symbol_type] === 'string') {
var symbol = this.settings.symbols[this.settings.selected_symbol_type];
this.settings.symbols[this.settings.selected_symbol_type] = {};
this.settings.symbols[this.settings.selected_symbol_type]['base'] = symbol;
this.settings.symbols[this.settings.selected_symbol_type]['selected'] = symbol;
this.settings.symbols[this.settings.selected_symbol_type]['hover'] = symbol;
}
/*
* Making the three main layers (base, select, hover)
*/
var base_layer = this.addLayer("base-layer", 100, this.settings.symbols[
this.settings.selected_symbol_type]["base"], true);
var select_layer = this.addLayer("select-layer", selected_width,
this.settings.symbols[this.settings.selected_symbol_type]["selected"], true);
var hover_layer = this.addLayer("hover-layer", 0, this.settings.symbols[
this.settings.selected_symbol_type]["hover"], false);
/* var face_layer = this.addLayer("face-layer", 1, this.settings
.symbols[this.settings.face_layer_symbol_type][0], true); */
this.layers["base_layer"] = base_layer;
this.layers["select_layer"] = select_layer;
this.layers["hover_layer"] = hover_layer;
/*
* Bind the container to some events
*/
$(this.element).on("mousemove", $.proxy(this.hover, this));
$(this.element).on("click", $.proxy(this.select, this));
$(this.element).on("mouseleave", $.proxy(this.mouseout, this));
/*
* Set the main element as unselectable
*/
$(this.element).css({
"-webkit-touch-callout": "none",
"-webkit-user-select": "none",
"-khtml-user-select": "none",
"-moz-user-select": "none",
"-ms-user-select": "none",
"user-select": "none",
});
/*
* Update custom input field if provided
*/
if (this.settings.hasOwnProperty("update_input_field_name")) {
this.settings.update_input_field_name.val(this.value);
}
}
/*
* Function to add a layer
*/
Rate.prototype.addLayer = function (layer_name, visible_width, symbol, visible) {
var layer_body = "<div>";
for (var i = 0; i < this.settings.max_value; i++) {
if (Array.isArray(symbol)) {
if (this.settings.convert_to_utf8) {
symbol[i] = String.fromCodePoint(symbol[i]);
}
layer_body += "<span>" + (symbol[i]) + "</span>";
}
else {
if (this.settings.convert_to_utf8) {
symbol = String.fromCodePoint(symbol);
}
layer_body += "<span>" + symbol + "</span>";
}
}
layer_body += "</div>";
var layer = $(layer_body).addClass("rate-" + layer_name).appendTo(this.element);
$(layer).css({
width: visible_width + "%",
height: $(layer).children().eq(0).textHeight(),
overflow: 'hidden',
position: 'absolute',
top: 0,
display: visible ? 'block' : 'none',
'white-space': 'nowrap'
});
$(this.element).css({
width: $(layer).textWidth() + "px",
height: $(layer).height(),
position: 'relative',
cursor: this.settings.cursor,
});
return layer;
}
Rate.prototype.updateServer = function () {
if (this.settings.url != undefined) {
$.ajax({
url: this.settings.url,
type: this.settings.ajax_method,
data: $.extend({}, { value: this.getValue() }, this.settings.additional_data),
success: $.proxy(function (data) {
$(this.element).trigger("updateSuccess", [data]);
}, this),
error: $.proxy(function (jxhr, msg, err) {
$(this.element).trigger("updateError", [jxhr, msg, err]);
}, this)
});
}
}
Rate.prototype.getValue = function () {
return this.value;
}
Rate.prototype.hover = function (ev) {
var pad = parseInt($(this.element).css("padding-left").replace("px", ""));
var x = ev.pageX - $(this.element).offset().left - pad;
var val = this.toValue(x, true);
if (val != this.value) {
this.raise_select_layer = false;
}
if (!this.raise_select_layer && !this.settings.readonly) {
var visible_width = this.toWidth(val);
this.layers.select_layer.css({ display: 'none' });
if (!this.settings.only_select_one_symbol) {
this.layers.hover_layer.css({
width: visible_width + "%",
display: 'block'
});
}
else {
var index_value = Math.floor(val);
this.layers.hover_layer.css({
width: "100%",
display: 'block'
});
this.layers.hover_layer.children("span").css({
visibility: 'hidden',
});
this.layers.hover_layer.children("span").eq(index_value != 0 ? index_value - 1 : 0).css({
visibility: 'visible',
});
}
}
}
/*
* Event for when a rating has been selected (clicked)
*/
Rate.prototype.select = function (ev) {
if (!this.settings.readonly) {
var old_value = this.getValue();
var pad = parseInt($(this.element).css("padding-left").replace("px", ""));
var x = ev.pageX - $(this.element).offset().left - pad;
var selected_width = this.toWidth(this.toValue(x, true));
this.setValue(this.toValue(selected_width));
this.raise_select_layer = true;
}
}
Rate.prototype.mouseout = function () {
this.layers.hover_layer.css({ display: 'none' });
this.layers.select_layer.css({ display: 'block' });
}
/*
* Takes a width (px) and returns the value it resembles
*/
Rate.prototype.toWidth = function (val) {
return val / this.settings.max_value * 100;
}
/*
* Takes a value and calculates the width of the selected/hovered layer
*/
Rate.prototype.toValue = function (width, in_pixels) {
var val;
if (in_pixels) {
val = width / this.layers.base_layer.textWidth() * this.settings.max_value;
}
else {
val = width / 100 * this.settings.max_value;
}
// Make sure the division doesn't cause some small numbers added by
// comparing to a small arbitrary number.
var temp = val / this.settings.step_size;
if (temp - Math.floor(temp) < 0.00005) {
val = Math.round(val / this.settings.step_size) * this.settings.step_size;
}
val = (Math.ceil(val / this.settings.step_size)) * this.settings.step_size;
val = val > this.settings.max_value ? this.settings.max_value : val;
return val;
}
Rate.prototype.getElement = function (layer_name, index) {
return $(this.element).find(".rate-" + layer_name + " span").eq(index - 1);
}
Rate.prototype.getLayers = function () {
return this.layers;
}
Rate.prototype.setFace = function (value, face) {
this.set_faces[value] = face;
}
Rate.prototype.setAdditionalData = function (data) {
this.settings.additional_data = data;
}
Rate.prototype.getAdditionalData = function () {
return this.settings.additional_data;
}
Rate.prototype.removeFace = function (value) {
delete this.set_faces[value];
}
Rate.prototype.setValue = function (value) {
if (!this.settings.readonly) {
if (value < 0) {
value = 0;
}
else if (value > this.settings.max_value) {
value = this.settings.max_value;
}
var old_value = this.getValue();
this.value = value;
/*
* About to change event, should support prevention later
*/
var change_event = $(this.element).trigger("change", {
"from": old_value,
"to": this.value
});
/*
* Set/Reset faces
*/
$(this.element).find(".rate-face").remove();
$(this.element).find("span").css({
visibility: 'visible'
});
var index_value = Math.ceil(this.value);
if (this.set_faces.hasOwnProperty(index_value)) {
var face = "<div>" + this.set_faces[index_value] + "</div>";
var base_layer_element = this.getElement('base-layer', index_value);
var select_layer_element = this.getElement('select-layer', index_value);
var hover_layer_element = this.getElement('hover-layer', index_value);
var left_pos = base_layer_element.textWidth() * (index_value - 1)
+ (base_layer_element.textWidth() - $(face).textWidth()) / 2;
$(face).appendTo(this.element).css({
display: 'inline-block',
position: 'absolute',
left: left_pos,
}).addClass("rate-face");
base_layer_element.css({
visibility: 'hidden'
});
select_layer_element.css({
visibility: 'hidden'
});
hover_layer_element.css({
visibility: 'hidden'
});
}
/*
* Set styles based on width and value
*/
if (!this.settings.only_select_one_symbol) {
var width = this.toWidth(this.value);
this.layers.select_layer.css({
display: 'block',
width: width + "%",
height: this.layers.base_layer.css("height")
});
this.layers.hover_layer.css({
display: 'none',
height: this.layers.base_layer.css("height")
});
}
else {
var width = this.toWidth(this.settings.max_value);
this.layers.select_layer.css({
display: 'block',
width: width + "%",
height: this.layers.base_layer.css("height")
});
this.layers.hover_layer.css({
display: 'none',
height: this.layers.base_layer.css("height")
});
this.layers.select_layer.children("span").css({
visibility: 'hidden',
});
this.layers.select_layer.children("span").eq(index_value != 0 ? index_value - 1 : 0).css({
visibility: 'visible',
});
}
// Update the data-rate-value attribute
$(this.element).attr("data-rate-value", this.value);
if (this.settings.change_once) {
this.settings.readonly = true;
}
this.updateServer();
/*
* After change event
*/
var change_event = $(this.element).trigger("afterChange", {
"from": old_value,
"to": this.value
});
/*
* Update custom input field if provided
*/
if (this.settings.hasOwnProperty("update_input_field_name")) {
this.settings.update_input_field_name.val(this.value);
}
}
}
Rate.prototype.increment = function () {
this.setValue(this.getValue() + this.settings.step_size);
}
Rate.prototype.decrement = function () {
this.setValue(this.getValue() - this.settings.step_size);
}
$.fn.rate.settings = {
max_value: 5,
step_size: 0.5,
initial_value: 0,
symbols: {
utf8_star: {
base: '\u2606',
hover: '\u2605',
selected: '\u2605',
},
utf8_hexagon: {
base: '\u2B21',
hover: '\u2B22',
selected: '\u2B22',
},
hearts: '♥',
fontawesome_beer: '<i class="fa fa-beer"></i>',
fontawesome_star: {
base: '<i class="fa fa-star-o"></i>',
hover: '<i class="fa fa-star"></i>',
selected: '<i class="fa fa-star"></i>',
},
utf8_emoticons: {
base: [0x1F625, 0x1F613, 0x1F612, 0x1F604],
hover: [0x1F625, 0x1F613, 0x1F612, 0x1F604],
selected: [0x1F625, 0x1F613, 0x1F612, 0x1F604],
},
},
selected_symbol_type: 'utf8_star', // Must be a key from symbols
convert_to_utf8: false,
cursor: 'default',
readonly: false,
change_once: false, // Determines if the rating can only be set once
only_select_one_symbol: false, // If set to true, only selects the hovered/selected symbol and nothing prior to it
ajax_method: 'POST',
additional_data: {}, // Additional data to send to the server
//update_input_field_name = some input field set by the user
};
}(jQuery, window));
//$(".rating").rate();
//or for example
var options = {
max_value: 5,
step_size: 1,
}
$(".rating").rate(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rating" data-rate-value=6></div>
You are specifying the options at an earlier stage in your code.
See here:
$.fn.rate.settings = {
max_value: 5,
step_size: 0.5,
I tested in your fiddle and it works when updated to 1 step_size.
I'm integrating FabricJS into my angular application. I've managed to get the canvas down and automatically adding a figure into the canvas.
My goals are to make the figure 8inches by 8inches and to add a grid that has dynamic grid height and width (lets say 1/16th inch x 1/16inch).
Here are my problems:
1. When adding the figure, I cannot set the figure height and width in inches. I can only use a number. How can I use a different unit for this? I used cssOnly: true for the canvas but I cant seem to figure it out for the figure.
addFigure(figure) {
let add: any;
switch (figure) {
case 'rectangle':
add = new fabric.Rect({
width: 500, height: 500, left: 150, top: 10, angle: 0, opacity: .3,
fill: '#3f51b5'
});
break;
case 'square':
add = new fabric.Rect({
width: 200, height: 200, left: 0, top: 0, angle: 0, opacity: .15,
fill: '#4caf50'
});
break;
case 'triangle':
add = new fabric.Triangle({
width: 100, height: 100, left: 10, top: 10, fill: '#2196f3'
});
break;
case 'circle':
add = new fabric.Circle({
radius: 50, left: 10, top: 10, fill: '#ff5722'
});
break;
}
this.extend(add, this.randomId());
console.log(add);
this.canvas.add(add);
// this.selectItemAfterAdded(add);
}
The figure height displays 200 but it appears incorrect. Here is an example of the above figure as a square. Notice the 200 width is correct but the height does not seem right seeing as the canvas is 6inches by 6inches. The height extends pass the bottom of the canvas.
Notice the grid above. Im having the same problem. Here is my code for grid which I pulled from Adding grid over Fabric.js canvas . The problem I'm having is I have no idea how to make this grid evenly 1/16th inch 1/16th inch given this is an 8in by 8in canvas.
onst gridGroup = new fabric.Group([], {left: 0, top: 0});
const gridSize = 16;
const gridWidth = 400;
const gridHeight = 400;
const lineOption = {stroke: 'rgba(0,0,0,.4)', strokeWidth: 1, selectable: false, strokeDashArray: [3, 3]};
for (let i = Math.ceil(gridWidth / gridSize); i--;) {
this.canvas.add( new fabric.Line([gridSize * i, 0, gridSize * i, gridHeight], lineOption) );
}
for (let i = Math.ceil(gridHeight / gridSize); i--;) {
this.canvas.add( new fabric.Line([0, gridSize * i, gridWidth, gridSize * i], lineOption) );
}
this.canvas.add(gridGroup);
Here is the entire component for review. Is there something I'm doing wrong in the setup?
// private canvas: any;
uploading = false;
uploaded = false;
pdfUrl = '';
canvas: any;
props: any = {
canvasFill: '#ffffff',
canvasImage: '',
id: null,
opacity: null,
fill: null,
fontSize: null,
lineHeight: null,
charSpacing: null,
fontWeight: null,
fontStyle: null,
textAlign: null,
fontFamily: null,
TextDecoration: ''
};
textString: string;
url = '';
size: any = {
width: '6in',
height: '6in'
};
json: any;
globalEditor = false;
textEditor = false;
imageEditor = false;
figureEditor = false;
selected: any;
constructor(
private router: Router,
private userService: UserService,
private fileService: FileService
) { }
ngOnInit() {
this.getActive();
// this.activateCanvas();
//setup front side canvas
this.canvas = new fabric.Canvas('canvas', {
hoverCursor: 'pointer',
selection: true,
selectionBorderColor: 'blue'
});
this.canvas.on({
'object:moving': (e) => { },
'object:modified': (e) => { },
'object:selected': (e) => {
const selectedObject = e.target;
this.selected = selectedObject
selectedObject.hasRotatingPoint = true;
selectedObject.transparentCorners = false;
// selectedObject.cornerColor = 'rgba(255, 87, 34, 0.7)';
this.resetPanels();
if (selectedObject.type !== 'group' && selectedObject) {
this.getId();
this.getOpacity();
switch (selectedObject.type) {
case 'rect':
case 'circle':
case 'triangle':
this.figureEditor = true;
this.getFill();
break;
case 'i-text':
this.textEditor = true;
this.getLineHeight();
this.getCharSpacing();
this.getBold();
this.getFontStyle();
this.getFill();
this.getTextDecoration();
this.getTextAlign();
this.getFontFamily();
break;
case 'image':
break;
}
}
},
'selection:cleared': (e) => {
this.selected = null;
this.resetPanels();
}
});
this.canvas.setWidth(this.size.width, {cssOnly: true});
this.canvas.setHeight(this.size.height, {cssOnly: true});
this.addFigure('square');
const gridGroup = new fabric.Group([], {left: 0, top: 0});
const gridSize = 16;
const gridWidth = 400;
const gridHeight = 400;
const lineOption = {stroke: 'rgba(0,0,0,.4)', strokeWidth: 1, selectable: false, strokeDashArray: [3, 3]};
for (let i = Math.ceil(gridWidth / gridSize); i--;) {
this.canvas.add( new fabric.Line([gridSize * i, 0, gridSize * i, gridHeight], lineOption) );
}
for (let i = Math.ceil(gridHeight / gridSize); i--;) {
this.canvas.add( new fabric.Line([0, gridSize * i, gridWidth, gridSize * i], lineOption) );
}
this.canvas.add(gridGroup);
// for ( let x = 1; x < ( this.canvas.width / gridsize); x++) {
// this.canvas.add(new fabric.Line([cellWidth * x, 0, cellWidth * x, 800],
// { stroke: '#000000', strokeWidth: 1, selectable: false}));
// this.canvas.add(new fabric.Line([0, cellWidth * x, 800, cellWidth * x],
// { stroke: '#000000', strokeWidth: 1, selectable: false}));
// }
// get references to the html canvas element & its context
// this.canvas.on('mouse:down', (e) => {
// let canvasElement: any = document.getElementById('canvas');
// console.log(canvasElement)
// });
}
/*------------------------Block elements------------------------*/
//Block "Size"
changeSize(event: any) {
this.canvas.setWidth(this.size.width);
this.canvas.setHeight(this.size.height);
}
//Block "Add text"
addText() {
let textString = this.textString;
let text = new fabric.IText(textString, {
left: 10,
top: 10,
fontFamily: 'helvetica',
angle: 0,
fill: '#000000',
scaleX: 0.5,
scaleY: 0.5,
fontWeight: '',
hasRotatingPoint: true
});
this.extend(text, this.randomId());
this.canvas.add(text);
this.selectItemAfterAdded(text);
this.textString = '';
}
//Block "Add images"
getImgPolaroid(event: any) {
let el = event.target;
fabric.Image.fromURL(el.src, (image) => {
image.set({
left: 10,
top: 10,
angle: 0,
padding: 10,
cornersize: 10,
hasRotatingPoint: true,
peloas: 12
});
// image.setWidth(150);
// image.setHeight(150);
this.extend(image, this.randomId());
this.canvas.add(image);
this.selectItemAfterAdded(image);
});
}
//Block "Upload Image"
addImageOnCanvas(url) {
if (url) {
fabric.Image.fromURL(url, (image) => {
image.set({
left: 10,
top: 10,
angle: 0,
// scaleX: 200,
// scaleY: 200,
padding: 10,
cornersize: 10,
hasRotatingPoint: true
});
image.scale(0.2);
// image.setWidth(200);
// image.height = 200;
// image.width = 200;
this.extend(image, this.randomId());
this.canvas.add(image);
this.selectItemAfterAdded(image);
});
}
}
readUrl(event) {
if (event.target.files && event.target.files[0]) {
const reader = new FileReader();
reader.onload = (e) => {
this.url = e.target['result'];
};
reader.readAsDataURL(event.target.files[0]);
}
}
removeWhite(url) {
this.url = '';
}
//Block "Add figure"
addFigure(figure) {
let add: any;
switch (figure) {
case 'rectangle':
add = new fabric.Rect({
width: 500, height: 500, left: 150, top: 10, angle: 0, opacity: .3,
fill: '#3f51b5'
});
break;
case 'square':
add = new fabric.Rect({
width: 200, height: 200, left: 0, top: 0, angle: 0, opacity: .4,
fill: '#4caf50'
});
break;
case 'triangle':
add = new fabric.Triangle({
width: 100, height: 100, left: 10, top: 10, fill: '#2196f3'
});
break;
case 'circle':
add = new fabric.Circle({
radius: 50, left: 10, top: 10, fill: '#ff5722'
});
break;
}
this.extend(add, this.randomId());
console.log(add);
this.canvas.add(add);
// this.selectItemAfterAdded(add);
}
/*Canvas*/
cleanSelect() {
this.canvas.discardActiveObject();
}
selectItemAfterAdded(obj) {
this.canvas.discardActiveObject();
this.canvas.setActiveObject(obj);
}
setCanvasFill() {
if (!this.props.canvasImage) {
this.canvas.backgroundColor = this.props.canvasFill;
this.canvas.renderAll();
}
}
extend(obj, id) {
obj.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
id: id
});
};
})(obj.toObject);
}
setCanvasImage() {
let self = this;
if (this.props.canvasImage) {
this.canvas.setBackgroundColor({ source: this.props.canvasImage, repeat: 'repeat' }, function () {
// self.props.canvasFill = '';
self.canvas.renderAll();
});
}
}
randomId() {
return Math.floor(Math.random() * 999999) + 1;
}
/*------------------------Global actions for element------------------------*/
getActiveStyle(styleName, object) {
object = object || this.canvas.getActiveObject();
if (!object) {return '';}
return (object.getSelectionStyles && object.isEditing)
? (object.getSelectionStyles()[styleName] || '')
: (object[styleName] || '');
}
setActiveStyle(styleName, value, object) {
object = object || this.canvas.getActiveObject();
if (!object) {return '';}
if (object.setSelectionStyles && object.isEditing) {
let style = {};
style[styleName] = value;
object.setSelectionStyles(style);
object.setCoords();
} else {
object.set(styleName, value);
}
object.setCoords();
this.canvas.renderAll();
}
getActiveProp(name) {
let object = this.canvas.getActiveObject();
if (!object) {return '';}
return object[name] || '';
}
setActiveProp(name, value) {
const object = this.canvas.getActiveObject();
if (!object) {return ''};
object.set(name, value).setCoords();
this.canvas.renderAll();
}
clone() {
const activeObject = this.canvas.getActiveObject(),
activeGroup = this.canvas.getActiveGroup();
if (activeObject) {
let clone;
switch (activeObject.type) {
case 'rect':
clone = new fabric.Rect(activeObject.toObject());
break;
case 'circle':
clone = new fabric.Circle(activeObject.toObject());
break;
case 'triangle':
clone = new fabric.Triangle(activeObject.toObject());
break;
case 'i-text':
clone = new fabric.IText('', activeObject.toObject());
break;
case 'image':
clone = fabric.util.object.clone(activeObject);
break;
}
if (clone) {
clone.set({ left: 10, top: 10 });
this.canvas.add(clone);
this.selectItemAfterAdded(clone);
}
}
}
getId() {
this.props.id = this.canvas.getActiveObject().toObject().id;
}
setId() {
const val = this.props.id;
const complete = this.canvas.getActiveObject().toObject();
console.log(complete);
this.canvas.getActiveObject().toObject = () => {
complete.id = val;
return complete;
};
}
getOpacity() {
this.props.opacity = this.getActiveStyle('opacity', null) * 100;
}
setOpacity() {
this.setActiveStyle('opacity', +this.props.opacity / 100, null);
}
getFill() {
this.props.fill = this.getActiveStyle('fill', null);
}
setFill() {
this.setActiveStyle('fill', this.props.fill, null);
}
getLineHeight() {
this.props.lineHeight = this.getActiveStyle('lineHeight', null);
}
setLineHeight() {
this.setActiveStyle('lineHeight', parseFloat(this.props.lineHeight), null);
}
getCharSpacing() {
this.props.charSpacing = this.getActiveStyle('charSpacing', null);
}
setCharSpacing() {
this.setActiveStyle('charSpacing', this.props.charSpacing, null);
}
getFontSize() {
this.props.fontSize = this.getActiveStyle('fontSize', null);
}
setFontSize() {
this.setActiveStyle('fontSize', +this.props.fontSize, null);
}
getBold() {
this.props.fontWeight = this.getActiveStyle('fontWeight', null);
}
setBold() {
this.props.fontWeight = !this.props.fontWeight;
this.setActiveStyle('fontWeight', this.props.fontWeight ? 'bold' : '', null);
}
getFontStyle() {
this.props.fontStyle = this.getActiveStyle('fontStyle', null);
}
setFontStyle() {
this.props.fontStyle = !this.props.fontStyle;
this.setActiveStyle('fontStyle', this.props.fontStyle ? 'italic' : '', null);
}
getTextDecoration() {
this.props.TextDecoration = this.getActiveStyle('textDecoration', null);
}
setTextDecoration(value) {
let iclass = this.props.TextDecoration;
if (iclass.includes(value)) {
iclass = iclass.replace(RegExp(value, 'g'), '');
} else {
iclass += ` ${value}`
}
this.props.TextDecoration = iclass;
this.setActiveStyle('textDecoration', this.props.TextDecoration, null);
}
hasTextDecoration(value) {
return this.props.TextDecoration.includes(value);
}
getTextAlign() {
this.props.textAlign = this.getActiveProp('textAlign');
}
setTextAlign(value) {
this.props.textAlign = value;
this.setActiveProp('textAlign', this.props.textAlign);
}
getFontFamily() {
this.props.fontFamily = this.getActiveProp('fontFamily');
}
setFontFamily() {
this.setActiveProp('fontFamily', this.props.fontFamily);
}
/*System*/
removeSelected() {
let activeObject = this.canvas.getActiveObject(),
activeGroup = this.canvas.getActiveGroup();
if (activeObject) {
this.canvas.remove(activeObject);
// this.textString = '';
} else if (activeGroup) {
let objectsInGroup = activeGroup.getObjects();
this.canvas.discardActiveGroup();
let self = this;
objectsInGroup.forEach(function (object) {
self.canvas.remove(object);
});
}
}
bringToFront() {
let activeObject = this.canvas.getActiveObject(),
activeGroup = this.canvas.getActiveGroup();
if (activeObject) {
activeObject.bringToFront();
// activeObject.opacity = 1;
}
else if (activeGroup) {
let objectsInGroup = activeGroup.getObjects();
this.canvas.discardActiveGroup();
objectsInGroup.forEach((object) => {
object.bringToFront();
});
}
}
sendToBack() {
const activeObject = this.canvas.getActiveObject(),
activeGroup = this.canvas.getActiveGroup();
if (activeObject) {
activeObject.sendToBack();
// activeObject.opacity = 1;
} else if (activeGroup) {
const objectsInGroup = activeGroup.getObjects();
this.canvas.discardActiveGroup();
objectsInGroup.forEach((object) => {
object.sendToBack();
});
}
}
confirmClear() {
if (confirm('Are you sure?')) {
this.canvas.clear();
}
}
rasterize() {
if (!fabric.Canvas.supports('toDataURL')) {
alert('This browser doesn\'t provide means to serialize canvas to an image');
} else {
console.log(this.canvas.toDataURL('png'))
//window.open(this.canvas.toDataURL('png'));
let image = new Image();
image.src = this.canvas.toDataURL('png')
let w = window.open('');
w.document.write(image.outerHTML);
}
}
rasterizeSVG() {
console.log(this.canvas.toSVG())
// window.open(
// 'data:image/svg+xml;utf8,' +
// encodeURIComponent(this.canvas.toSVG()));
// console.log(this.canvas.toSVG())
// let image = new Image();
// image.src = this.canvas.toSVG()
const w = window.open('');
w.document.write(this.canvas.toSVG());
}
saveCanvasToJSON() {
const json = JSON.stringify(this.canvas);
localStorage.setItem('Kanvas', json);
console.log('json');
console.log(json);
}
loadCanvasFromJSON() {
const CANVAS = localStorage.getItem('Kanvas');
console.log('CANVAS');
console.log(CANVAS);
// and load everything from the same json
this.canvas.loadFromJSON(CANVAS, () => {
console.log('CANVAS untar');
console.log(CANVAS);
// making sure to render canvas at the end
this.canvas.renderAll();
// and checking if object's "name" is preserved
console.log('this.canvas.item(0).name');
console.log(this.canvas);
});
}
rasterizeJSON() {
this.json = JSON.stringify(this.canvas, null, 2);
}
resetPanels() {
this.textEditor = false;
this.imageEditor = false;
this.figureEditor = false;
}
In summary, I'm looking to use a 1/16th inch x 1/16th inch (possibly dynamic) grid on an 8inch by 8inch canvas and add a figure that is also an even square inside this canvas.
For anyone having this same problem. It seems that the cssOnly boolean param option Im passing is not a solution for actually scaling the canvas to inches.
Here's how I resolved.
1) I now have an input that allows the user to manually enter in their PPI given the information on this url - http://dpi.lv/
2) I save that PPI
3) I created a method calcPixels(inches: number) which uses pixels = inches * ppi to calculate the number of pixels needed
4) I use that method across the application for all widths, heights, grid lines and etc.
This gives me a to scale 7in by 7inch grid line. Its a little less automated but if you save the PPI, the user only has to enter it once!
New result
I wanted to use this kind of Photo Collage on my Website: Seamless Photo Collage by AutomaticImageMontage
so I downloaded it and pasted the code to my Website..
it works but sometimes when the page loads the white background goes transparent on the whole page transperent background
I'm using Parallax and Bootstrap, sometimes the parallax isn't working properly too.
I have tried to set the background to white in CSS but nothing.. sometimes it loads normally but sometimes goes transparent,
I have checked the console too but it showes only
jquery.montage.min.js:1 Uncaught TypeError: Cannot read property 'apply' of undefined
now i really dont have any idea how to fix it.
please help :(
Javascript CSS and HTML
(function(window, $, undefined) {
Array.max = function(array) {
return Math.max.apply(Math, array)
};
Array.min = function(array) {
return Math.min.apply(Math, array)
};
var $event = $.event,
resizeTimeout;
$event.special.smartresize = {
setup: function() {
$(this).bind("resize", $event.special.smartresize.handler)
},
teardown: function() {
$(this).unbind("resize", $event.special.smartresize.handler)
},
handler: function(event, execAsap) {
var context = this,
args = arguments;
event.type = "smartresize";
if (resizeTimeout) {
clearTimeout(resizeTimeout)
}
resizeTimeout = setTimeout(function() {
jQuery.event.handle.apply(context, args)
}, execAsap === "execAsap" ? 0 : 50)
}
};
$.fn.smartresize = function(fn) {
return fn ? this.bind("smartresize", fn) : this.trigger("smartresize", ["execAsap"])
};
$.fn.imagesLoaded = function(callback) {
var $images = this.find('img'),
len = $images.length,
_this = this,
blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
function triggerCallback() {
callback.call(_this, $images)
}
function imgLoaded() {
if (--len <= 0 && this.src !== blank) {
setTimeout(triggerCallback);
$images.unbind('load error', imgLoaded)
}
}
if (!len) {
triggerCallback()
}
$images.bind('load error', imgLoaded).each(function() {
if (this.complete || this.complete === undefined) {
var src = this.src;
this.src = blank;
this.src = src
}
});
return this
};
$.Montage = function(options, element) {
this.element = $(element).show();
this.cache = {};
this.heights = new Array();
this._create(options)
};
$.Montage.defaults = {
liquid: true,
margin: 1,
minw: 70,
minh: 20,
maxh: 250,
alternateHeight: false,
alternateHeightRange: {
min: 100,
max: 300
},
fixedHeight: null,
minsize: false,
fillLastRow: false
};
$.Montage.prototype = {
_getImageWidth: function($img, h) {
var i_w = $img.width(),
i_h = $img.height(),
r_i = i_h / i_w;
return Math.ceil(h / r_i)
},
_getImageHeight: function($img, w) {
var i_w = $img.width(),
i_h = $img.height(),
r_i = i_h / i_w;
return Math.ceil(r_i * w)
},
_chooseHeight: function() {
if (this.options.minsize) {
return Array.min(this.heights)
}
var result = {},
max = 0,
res, val, min;
for (var i = 0, total = this.heights.length; i < total; ++i) {
var val = this.heights[i],
inc = (result[val] || 0) + 1;
if (val < this.options.minh || val > this.options.maxh) continue;
result[val] = inc;
if (inc >= max) {
max = inc;
res = val
}
}
for (var i in result) {
if (result[i] === max) {
val = i;
min = min || val;
if (min < this.options.minh) min = null;
else if (min > val) min = val;
if (min === null) min = val
}
}
if (min === undefined) min = this.heights[0];
res = min;
return res
},
_stretchImage: function($img) {
var prevWrapper_w = $img.parent().width(),
new_w = prevWrapper_w + this.cache.space_w_left,
crop = {
x: new_w,
y: this.theHeight
};
var new_image_w = $img.width() + this.cache.space_w_left,
new_image_h = this._getImageHeight($img, new_image_w);
this._cropImage($img, new_image_w, new_image_h, crop);
this.cache.space_w_left = this.cache.container_w;
if (this.options.alternateHeight) this.theHeight = Math.floor(Math.random() * (this.options.alternateHeightRange.max - this.options.alternateHeightRange.min + 1) + this.options.alternateHeightRange.min)
},
_updatePrevImage: function($nextimg) {
var $prevImage = this.element.find('img.montage:last');
this._stretchImage($prevImage);
this._insertImage($nextimg)
},
_insertImage: function($img) {
var new_w = this._getImageWidth($img, this.theHeight);
if (this.options.minsize && !this.options.alternateHeight) {
if (this.cache.space_w_left <= this.options.margin * 2) {
this._updatePrevImage($img)
} else {
if (new_w > this.cache.space_w_left) {
var crop = {
x: this.cache.space_w_left,
y: this.theHeight
};
this._cropImage($img, new_w, this.theHeight, crop);
this.cache.space_w_left = this.cache.container_w;
$img.addClass('montage')
} else {
var crop = {
x: new_w,
y: this.theHeight
};
this._cropImage($img, new_w, this.theHeight, crop);
this.cache.space_w_left -= new_w;
$img.addClass('montage')
}
}
} else {
if (new_w < this.options.minw) {
if (this.options.minw > this.cache.space_w_left) {
this._updatePrevImage($img)
} else {
var new_w = this.options.minw,
new_h = this._getImageHeight($img, new_w),
crop = {
x: new_w,
y: this.theHeight
};
this._cropImage($img, new_w, new_h, crop);
this.cache.space_w_left -= new_w;
$img.addClass('montage')
}
} else {
if (new_w > this.cache.space_w_left && this.cache.space_w_left < this.options.minw) {
this._updatePrevImage($img)
} else if (new_w > this.cache.space_w_left && this.cache.space_w_left >= this.options.minw) {
var crop = {
x: this.cache.space_w_left,
y: this.theHeight
};
this._cropImage($img, new_w, this.theHeight, crop);
this.cache.space_w_left = this.cache.container_w;
if (this.options.alternateHeight) this.theHeight = Math.floor(Math.random() * (this.options.alternateHeightRange.max - this.options.alternateHeightRange.min + 1) + this.options.alternateHeightRange.min);
$img.addClass('montage')
} else {
var crop = {
x: new_w,
y: this.theHeight
};
this._cropImage($img, new_w, this.theHeight, crop);
this.cache.space_w_left -= new_w;
$img.addClass('montage')
}
}
}
},
_cropImage: function($img, w, h, cropParam) {
var dec = this.options.margin * 2;
var $wrapper = $img.parent('a');
this._resizeImage($img, w, h);
$img.css({
left: -(w - cropParam.x) / 2 + 'px',
top: -(h - cropParam.y) / 2 + 'px'
});
$wrapper.addClass('am-wrapper').css({
width: cropParam.x - dec + 'px',
height: cropParam.y + 'px',
margin: this.options.margin
})
},
_resizeImage: function($img, w, h) {
$img.css({
width: w + 'px',
height: h + 'px'
})
},
_reload: function() {
var new_el_w = this.element.width();
if (new_el_w !== this.cache.container_w) {
this.element.hide();
this.cache.container_w = new_el_w;
this.cache.space_w_left = new_el_w;
var instance = this;
instance.$imgs.removeClass('montage').each(function(i) {
instance._insertImage($(this))
});
if (instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w) {
instance._stretchImage(instance.$imgs.eq(instance.totalImages - 1))
}
instance.element.show()
}
},
_create: function(options) {
this.options = $.extend(true, {}, $.Montage.defaults, options);
var instance = this,
el_w = instance.element.width();
instance.$imgs = instance.element.find('img');
instance.totalImages = instance.$imgs.length;
if (instance.options.liquid) $('html').css('overflow-y', 'scroll');
if (!instance.options.fixedHeight) {
instance.$imgs.each(function(i) {
var $img = $(this),
img_w = $img.width();
if (img_w < instance.options.minw && !instance.options.minsize) {
var new_h = instance._getImageHeight($img, instance.options.minw);
instance.heights.push(new_h)
} else {
instance.heights.push($img.height())
}
})
}
instance.theHeight = (!instance.options.fixedHeight && !instance.options.alternateHeight) ? instance._chooseHeight() : instance.options.fixedHeight;
if (instance.options.alternateHeight) instance.theHeight = Math.floor(Math.random() * (instance.options.alternateHeightRange.max - instance.options.alternateHeightRange.min + 1) + instance.options.alternateHeightRange.min);
instance.cache.container_w = el_w;
instance.cache.space_w_left = el_w;
instance.$imgs.each(function(i) {
instance._insertImage($(this))
});
if (instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w) {
instance._stretchImage(instance.$imgs.eq(instance.totalImages - 1))
}
$(window).bind('smartresize.montage', function() {
instance._reload()
})
},
add: function($images, callback) {
var $images_stripped = $images.find('img');
this.$imgs = this.$imgs.add($images_stripped);
this.totalImages = this.$imgs.length;
this._add($images, callback)
},
_add: function($images, callback) {
var instance = this;
$images.find('img').each(function(i) {
instance._insertImage($(this))
});
if (instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w) instance._stretchImage(instance.$imgs.eq(instance.totalImages - 1));
if (callback) callback.call($images)
},
destroy: function(callback) {
this._destroy(callback)
},
_destroy: function(callback) {
this.$imgs.removeClass('montage').css({
position: '',
width: '',
height: '',
left: '',
top: ''
}).unwrap();
if (this.options.liquid) $('html').css('overflow', '');
this.element.unbind('.montage').removeData('montage');
$(window).unbind('.montage');
if (callback) callback.call()
},
option: function(key, value) {
if ($.isPlainObject(key)) {
this.options = $.extend(true, this.options, key)
}
}
};
var logError = function(message) {
if (this.console) {
console.error(message)
}
};
$.fn.montage = function(options) {
if (typeof options === 'string') {
var args = Array.prototype.slice.call(arguments, 1);
this.each(function() {
var instance = $.data(this, 'montage');
if (!instance) {
logError("cannot call methods on montage prior to initialization; " + "attempted to call method '" + options + "'");
return
}
if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
logError("no such method '" + options + "' for montage instance");
return
}
instance[options].apply(instance, args)
})
} else {
this.each(function() {
var instance = $.data(this, 'montage');
if (instance) {
instance.option(options || {});
instance._reload()
} else {
$.data(this, 'montage', new $.Montage(options, this))
}
})
}
return this
}
})(window, jQuery);
.am-wrapper{
float:left;
position:relative;
overflow:hidden;
}
.am-wrapper img{
position:absolute;
outline:none;
}
<div class="container">
<div id="am-container" class="am-container"><img src="images/1.jpg"><img src="images/2.jpg"><img src="images/3.jpg"><img src="images/4.jpg"><img src="images/5.jpg"><img src="images/6.jpg"><img src="images/7.jpg"><img src="images/8.jpg"><img src="images/9.jpg"><img src="images/10.jpg"><img src="images/11.jpg"><img src="images/12.jpg"><img src="images/13.jpg"><img src="images/14.jpg"><img src="images/15.jpg"><img src="images/16.jpg"><img src="images/17.jpg"><img src="images/18.jpg"><img src="images/19.jpg">
</div>
</div>
<script type="text/javascript">
$(function() {
var $container = $('#am-container'),
$imgs = $container.find('img').hide(),
totalImgs = $imgs.length,
cnt = 0;
$imgs.each(function(i) {
var $img = $(this);
$('<img/>').load(function() {
++cnt;
if( cnt === totalImgs ) {
$imgs.show();
$container.montage({
fillLastRow : false,
alternateHeight : false,
alternateHeightRange : {
min : 90,
max : 100
}
});
}
}).attr('src',$img.attr('src'));
});
});
</script>
my question is really simple and something can help a lot of people out there,
I want my slideshow to NOT stop when someone hover over it,
I was able to do it for one of my sites, by accessing the .js (nivooSlider.js) and adding to the list of options: the "false" value to the pauseOnHover option (pauseOnHover: false,)
and that did it! ...
Now I'm also trying to get the same result in another of my websites that is currently using rokSlider, which does not have that option by default, so i'm wondering, if i go to the options list and simple add this options+value ... Do you think that will work?
Regards
var Slideshow = new Class({
version: '3.0.3',
options: {
captions: true,
showTitleCaption: true,
classes: ['prev', 'next', 'active'],
duration: [2000, 4000],
path: '/',
navigation: false,
pan: 100,
resize: true,
thumbnailre: [/\./, 't.'],
transition: Fx.Transitions.Sine.easeInOut,
type: 'fade',
zoom: 50,
loadingDiv: true,
removeDiv: true
},
styles: {
caps: {
div: {
opacity: 0,
position: 'absolute',
width: '100%',
margin: 0,
left: 0,
bottom: 0,
height: 40,
background: '#333',
color: '#fff',
textIndent: 0
},
h2: {
color: 'red',
padding: 0,
fontSize: '80%',
margin: 0,
margin: '2px 5px',
fontWeight: 'bold'
},
p: {
padding: 0,
fontSize: '60%',
margin: '2px 5px',
color: '#eee'
}
}
},
initialize: function(el, options) {
this.setOptions($merge({
onClick: this.onClick.bind(this)
}, options));
if(!this.options.images) return;
this.options.pan = this.mask(this.options.pan);
this.options.zoom = this.mask(this.options.zoom);
this.el = $(el).empty();
this.caps = {
div: new Element('div', {
styles: this.styles.caps.div,
'class': 'captionDiv'
}),
h2: new Element('h2', {
styles: this.styles.caps.h2,
'class': 'captionTitle'
}),
p: new Element('p', {
styles: this.styles.caps.p,
'class': 'captionDescription'
})
};
this.fx = [];
var trash = new ImageLoader(this.el, this.options.images, {
loadingDiv: this.options.loadingDiv,
onComplete: this.start.bind(this),
path: this.options.path,
removeDiv: this.options.removeDiv
});
},
start: function() {
this.imgs = $A(arguments);
this.a = this.imgs[0].clone().set({
styles: {
display: 'block',
position: 'absolute',
left: 0,
'top': 0,
zIndex: 1
}
}).injectInside(this.el);
var obj = this.a.getCoordinates();
this.height = this.options.height || obj.height;
this.width = this.options.width || obj.width;
this.el.setStyles({
display: 'block',
position: 'relative',
width: this.width
});
this.el.empty();
this.el.adopt((new Element('div', {
events: {
'click': this.onClick.bind(this)
},
styles: {
display: 'block',
overflow: 'hidden',
position: 'relative',
width: this.width,
height: this.height
}
})).adopt(this.a));
this.resize(this.a, obj);
this.b = this.a.clone().setStyle('opacity', 0).injectAfter(this.a);
this.timer = [0, 0];
this.navigation();
this.direction = 'left';
this.curr = [0,0];
$(document.body).adopt(new Element('div', {
id: 'hiddenDIV',
styles: {
visibility: 'hidden',
height: 0,
width: 0,
overflow: 'hidden',
opacity: 0
}
}));
this.loader = this.imgs[0];
$('hiddenDIV').adopt(this.loader);
this.load();
},
load: function(fast) {
if ($time() > this.timer[0]) {
this.img = (this.curr[1] % 2) ? this.b : this.a;
this.img.setStyles({
opacity: 0,
width: 'auto',
height: 'auto',
zIndex: this.curr[1]
});
var url = this.options.images[this.curr[0]].url;
this.img.setStyle('cursor', (url != '#' && url != '') ? 'pointer' : 'default');
this.img.setProperties({
src: this.loader.src,
title: this.loader.title,
alt: this.loader.alt
});
this.resize(this.img, this.loader);
if(fast){
this.img.setStyles({
top: 0,
left: 0,
opacity: 1
});
this.captions();
this.loaded();
return;
}
this.captions();
this[this.options.type.test(/push|wipe/) ? 'swipe' : 'kens']();
this.loaded();
} else {
this.timeout = this.load.delay(100, this);
}
},
loaded: function() {
if(this.ul) {
this.ul.getElements('a[name]').each(function(a, i) {
a[(i === this.curr[0] ? 'add' : 'remove') + 'Class'](this.options.classes[2]);
}, this);
}
this.direction = 'left';
this.curr[0] = (this.curr[0] + 1) % this.imgs.length;
this.curr[1]++;
this.timer[0] = $time() + this.options.duration[1] + (this.options.type.test(/fade|push|wipe/) ? this.options.duration[0] : 0);
this.timer[1] = $time() + this.options.duration[0];
this.loader = this.imgs[this.curr[0]];
$('hiddenDIV').empty().adopt(this.loader);
this.load();
},
kens: function() {
this.img.setStyles({
bottom: 'auto',
right: 'auto',
left: 'auto',
top: 'auto'
});
var arr = ['left top', 'right top', 'left bottom', 'right bottom'].getRandom().split(' ');
arr.each(function(p) {
this.img.setStyle(p, 0);
}, this);
var zoom = this.options.type.test(/zoom|combo/) ? this.zoom() : {};
var pan = this.options.type.test(/pan|combo/) ? this.pan(arr) : {};
this.fx.push(this.img.effect('opacity', {duration: this.options.duration[0]}).start(1));
this.fx.push(this.img.effects({duration: this.options.duration[0] + this.options.duration[1]}).start($merge(zoom, pan)));
},
zoom: function() {
var n = Math.max(this.width / this.loader.width, this.height / this.loader.height);
var z = (this.options.zoom === 'rand') ? Math.random() + 1 : (this.options.zoom.toInt() / 100.0) + 1;
var eh = Math.ceil(this.loader.height * n);
var ew = Math.ceil(this.loader.width * n);
var sh = (eh * z).toInt();
var sw = (ew * z).toInt();
return {height: [sh, eh], width: [sw, ew]};
},
pan: function(arr) {
var ex = this.width - this.img.width, ey = this.height - this.img.height;
var p = this.options.pan === 'rand' ? Math.random() : Math.abs((this.options.pan.toInt() / 100) - 1);
var sx = (ex * p).toInt(), sy = (ey * p).toInt();
var x = this.width / this.loader.width > this.height / this.loader.height;
var obj = {};
obj[arr[x ? 1 : 0]] = x ? [sy, ey] : [sx, ex];
return obj;
},
swipe: function() {
var arr, p0 = {}, p1 = {}, x;
this.img.setStyles({
left: 'auto',
right: 'auto',
opacity: 1
}).setStyle(this.direction, this.width);
if(this.options.type === 'wipe') {
this.fx.push(this.img.effect(this.direction, {
duration: this.options.duration[0],
transition: this.options.transition
}).start(0));
} else {
arr = [this.img, this.curr[1] % 2 ? this.a : this.b];
p0[this.direction] = [this.width, 0];
p1[this.direction] = [0, -this.width];
if(arr[1].getStyle(this.direction) === 'auto') {
x = this.width - arr[1].getStyle('width').toInt();
arr[1].setStyle(this.direction, x);
arr[1].setStyle(this.direction === 'left' ? 'right' : 'left', 'auto');
p1[this.direction][0] = x;
}
this.fx.push(new Fx.Elements(arr, {
duration: this.options.duration[0],
transition: this.options.transition
}).start({
'0': p0,
'1': p1
}));
}
},
captions: function(img) {
img = img || this.img;
if(!this.options.captions || (!img.title && !img.alt)) return;
this.el.getFirst().adopt(this.caps.div.adopt(this.caps.h2, this.caps.p));
(function () {
if (this.options.showTitleCaption) this.caps.h2.setHTML(img.title);
this.caps.p.setHTML(img.alt);
this.caps.div.setStyle('zIndex', img.getStyle('zIndex')*2 || 10);
this.capsHeight = this.capsHeight || this.options.captionHeight || this.caps.div.offsetHeight;
var fx = this.caps.div.effects().set({'height': 0}).start({
opacity: 0.7,
height: this.capsHeight
});
(function(){
fx.start({
opacity: 0,
height: 0
});
}).delay(1.00*(this.options.duration[1] - this.options.duration[0]));
}).delay(0.75*(this.options.duration[0]), this);
},
navigation: function() {
if(!this.options.navigation) return;
var i, j, atemp;
var fast = this.options.navigation.test(/fast/) ;
this.ul = new Element('ul');
var li = new Element('li'), a = new Element('a');
if (this.options.navigation.test(/arrows/)) {
this.ul.adopt(li.clone()
.adopt(a.clone()
.addClass(this.options.classes[0])
.addEvent('click', function() {
if (fast || $time() > this.timer[1]) {
$clear(this.timeout);
// Clear the FX array only for fast navigation since this stops combo effects
if(fast) {
this.fx.each(function(fx) {
fx.time = 0;
fx.options.duration = 0;
fx.stop(true);
});
}
this.direction = 'right';
this.curr[0] = (this.curr[0] < 2) ? this.imgs.length - (2 - this.curr[0]) : this.curr[0] - 2;
this.timer = [0];
this.loader = this.imgs[this.curr[0]];
this.load(fast);
}
}.bind(this))
)
);
}
if (this.options.navigation.test(/arrows\+|thumbnails/)) {
for (i = 0, j = this.imgs.length; i < j; i++) {
atemp = a.clone().setProperty('name', i);
if (this.options.navigation.test(/thumbnails/)) atemp.setStyle('background-image', 'url(' + this.imgs[i].src + ')');
if(i === 0) a.className = this.options.classes[2];
atemp.onclick = function(i) {
if(fast || $time() > this.timer[1]) {
$clear(this.timeout);
if (fast) {
this.fx.each(function(fx) {
fx.time = 0;
fx.options.duration = 0;
fx.stop(true);
});
}
this.direction = (i < this.curr[0] || this.curr[0] === 0) ? 'right' : 'left';
this.curr[0] = i;
this.timer = [0];
this.loader = this.imgs[this.curr[0]];
this.load(fast);
}
}.pass(i, this);
this.ul.adopt(li.clone().adopt(atemp));
}
}
if (this.options.navigation.test(/arrows/)) {
this.ul.adopt(li.clone()
.adopt(a.clone()
.addClass(this.options.classes[1])
.addEvent('click', function() {
if (fast || $time() > this.timer[1]) {
$clear(this.timeout);
// Clear the FX array only for fast navigation since this stops combo effects
if (fast) {
this.fx.each(function(fx) {
fx.time = 0;
fx.options.duration = 0;
fx.stop(true);
});
}
this.timer = [0];
this.load(fast);
}
}.bind(this))
)
);
}
this.ul.injectInside(this.el);
},
onClick: function(e) {
e = new Event(e).stop();
var cur = this.curr[1] % this.imgs.length;
var index = this.curr[1] == 0 ? 1 : cur == 0 ? this.imgs.length : cur;
var url = this.options.images[index - 1].url;
if(url == '#' || url == '') return;
window.location.href = url;
},
mask: function(val, set, lower, higher) {
if(val != 'rand') {
val = val.toInt();
val = isNaN(val) || val < lower || val > higher ? set : val;
}
return val;
},
resize: function(obj, to) {
var n;
if(this.options.resize) {
n = Math.max(this.width / to.width, this.height / to.height);
obj.setStyles({
height: Math.ceil(to.height*n),
width: Math.ceil(to.width*n)
});
}
}
});
Slideshow.implement(new Options);
/**
*
*
*
*/
var ImageLoader = new Class({
version:'.5-olmo-ver',
options: {
loadingDiv : false,
loadingPrefix : 'loading images: ',
loadingSuffix : '',
path : '',
removeDiv : true
},
initialize: function(container, sources, options){
this.setOptions(options);
this.loadingDiv = (this.options.loadingDiv) ? $(container) : false;
this.images = [];
this.index = 0;
this.total = sources.length;
if(this.loadingDiv) {
this.loadingText = new Element('div').injectInside(this.loadingDiv);
this.progressBar = new Element('div', {
styles: {
width: 100,
padding: 1,
margin: '5px auto',
textAlign: 'left',
overflow: 'hidden',
border: 'solid 1px #333'
}
}).adopt(new Element('div', {
styles: {
width: '0%',
height: 10,
backgroundColor: '#333'
}
})).injectInside(this.loadingDiv);
}
this.loadImages.delay(200, this, [sources]);
},
reset: function() {
this.index = 0;
if(this.loadingDiv) {
this.progressBar.getFirst().setStyle('width', '0%');
this.loadingText.setHTML(this.options.loadingPrefix);
}
},
loadImages: function(sources) {
var self = this;
this.reset();
this.images = [];
this.sources = sources;
this.timer = setInterval(this.loadProgress.bind(this), 100);
for(var i = 0, j = sources.length; i < j; i++) {
this.images[i] = new Asset.image((this.sources[i].path || this.options.path) + this.sources[i].file, {
title: self.sources[i].title,
alt: self.sources[i].desc,
'onload' : function(){ self.index++; },
'onerror' : function(){ self.index++; self.images.splice(i,1); },
'onabort' : function(){ self.index++; self.images.splice(i,1); }
});
}
},
loadProgress: function() {
if(this.loadingDiv) {
this.loadingText.setHTML(this.options.loadingPrefix + this.index + '/' + this.total + this.options.loadingSuffix);
this.progressBar.getFirst().setStyle('width', (!this.total ? 0 : this.index.toInt()*100 / this.total) + '%');
}
if(this.index >= this.total) {
this.loadComplete();
}
},
loadComplete: function(){
$clear(this.timer);
if(this.loadingDiv) {
this.loadingText.setHTML('Loading Complete');
if(this.options.removeDiv) {
this.loadingText.empty().remove();
this.progressBar.empty().remove();
}
}
this.fireEvent('onComplete', this.images);
},
cancel: function(){
$clear(this.timer);
}
});
ImageLoader.implement(new Events, new Options);
If the slider stops on mouseover event, you can try:
$('#sliderSelector').mouseover(function (event) {
event.stopPropagation();
event.preventDefault();
});
or:
$('#sliderSelector').mouseover(function () {
return false;
});
If the function in the plugin is only stoping the slider, then it should work. If there's more behind it will probably fail.
If this is not working: can you provide plugin code? (I coudnt't find it using google)