How can I optimize this code? A Javascript loop showing images - javascript

I've created a loop in Javascript that shows a new image every 2 seconds.
Additionally, it shows a new image also when the user move the mouse, but this is not an issue.
The problem is that the CPU usage is not as low as I would expect: 7-10% on PC and if I open the website on my mobile it slows down too much...
Other things to say are that this is part of a Nuxt 3 project and I tried both to put this in a plugin or under a component script section with the same result.
Here is the code part of the main "loop".
Initially I fetch the images from the backend and keep them in img elements that I then clone for better performance.
Then it starts looping with "window.requestAnimationFrame".
In order to have some improvements, I generate an arbitrary amount of images (30 if mobile, 60 on desktops) and then I just reuse them.
import { Point, AnchorWork } from './extra/types';
import * as utils from './extra/utils';
export default defineNuxtPlugin(async () => {
async function start() {
const { find } = useStrapi(),
apiUrl = useApi(),
isMobile = useMobile(),
baseLink = document.createElement('a');
try {
let loadedImages = 0;
const pics = await find('works', { populate: '*' }),
rawImages = [],
totalImages = Object.keys(pics.data).length;
pics.data.forEach((pic) => {
const picUrl = apiUrl + (isMobile ? pic.attributes.image.data.attributes.formats.medium.url : pic.attributes.image.data.attributes.formats.xlarge.url);
const img = new Image();
img.addEventListener('load', async () => {
const link = baseLink.cloneNode();
link.appendChild(img);
rawImages.push(link);
if (++loadedImages >= totalImages) {
utils.delay(100).then(async () => {
//document.getElementById('loader').style.opacity = '0';
await loop(rawImages, totalImages);
});
}
});
img.src = picUrl;
img.alt = pic.attributes.name;
})
} catch(error) {
console.log(error);
return;
}
}
await start();
async function loop(pictures, max) {
const isMobile = useMobile(),
maxQueue = isMobile ? 30 : 60,
imagesQueue = [],
delay = 2000,
baseDiv = document.createElement('div'),
body = document.body;
let auto = true,
picsContainer = document.getElementById('pictures'),
mainContainer = document.getElementById('main'),
mouseMinDelta = window.innerWidth * 0.1 + window.innerHeight * 0.1,
current = Math.floor( Math.random() * ( max - 3 ) ),
mouseTimeout,
resizeTimeout,
oldMouse = new Point(0, 0),
movement = new Point(0, 0);
async function generateImg(px, py) {
const { x, y } = px && py ? { x: px, y: py } : utils.generateCoord(picsContainer.clientWidth, picsContainer.clientHeight);
if(imagesQueue.length < maxQueue) {
if(current >= max) current = 0;
const link = new AnchorWork(pictures[current++].cloneNode(true), x, y);
await link.appendTo(picsContainer);
let overlay = baseDiv.cloneNode();
link.element.addEventListener('click', (e) => {
e.preventDefault();
workClick(link, overlay);
});
imagesQueue.push(link);
} else {
const index = imagesQueue[0].hasClass('active') ? 1 : 0;
const item = imagesQueue[index];
await item.removeClass('work');
item.position = new Point(x, y);
picsContainer.lastElementChild.after(item.element);
item.newSize();
imagesQueue.push(imagesQueue.splice(index, 1)[0]);
setTimeout(() => { item.addClass('work'); }, 200);
}
}
function workClick(link, overlay) {
const target = link;
if(target.hasClass('active')) {
target.childImage.resetStyle();
overlay.remove();
target.removeClass('active');
} else {
const height = body.clientHeight > body.clientWidth ? 'auto' : '100%';
const width = height == 'auto' ? '100%' : 'auto';
target.childImage.modStyle('height: ' + height + '; width: ' + width + ';');
overlay.classList.add('overlay');
overlay.addEventListener('click', overlay.remove);
picsContainer.appendChild(overlay);
target.appendTo(mainContainer);
target.addClass('active');
}
}
if(!isMobile) {
picsContainer.addEventListener('mousemove', (event) => {
clearTimeout(mouseTimeout);
mouseTimeout = setTimeout(() => {
picsContainer.dispatchEvent(new Event('mousestop'))
}, delay);
movement.x += Math.abs(event.pageX - oldMouse.x);
movement.y += Math.abs(event.pageY - oldMouse.y);
if(movement.x + movement.y > mouseMinDelta) {
generateImg(picsContainer.clientWidth - event.pageX, picsContainer.clientHeight - event.pageY);
movement.Set(0, 0);
}
oldMouse.Set(event.pageX, event.pageY);
auto = false;
});
picsContainer.addEventListener('mousestop', () => { auto = true; });
}
//Reposition images based on new window size
window.addEventListener('resize', () => {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(() => {
window.dispatchEvent(new Event('resizeend'))
}, 20);
});
window.addEventListener('resizeend', () => {
mouseMinDelta = window.innerWidth * 0.1 + window.innerHeight * 0.1;
imagesQueue.forEach(img => {
const coord = utils.generateCoord(picsContainer.clientWidth, picsContainer.clientHeight),
point = new Point(coord.x, coord.y);
if(!img.hasClass('active')) {
img.position = point;
img.newSize();
}
})
})
//Initial images
for(let x = 0; x < 3; x++) { generateImg(); }
async function animate() {
if(auto) {
generateImg();
}
await utils.delay(delay);
window.requestAnimationFrame(animate);
}
window.requestAnimationFrame(animate);
}
});
Here are some classes I created to help me:
import * as utils from './utils';
class BaseWork {
_width;
_height;
_style;
_element;
constructor(el) {
this._element = el;
const size = utils.generateSize();
this._width = size.width;
this._height = size.height;
this._style = '';
}
//Getters - Setters
get element() { return this._element; }
get width() { return this._width; }
get height() { return this._height; }
get style() { return this._style; }
set width(newWidth) { this._width = newWidth; }
set height(newHeight) { this._height = newHeight; }
set style(newStyle) {
this._style = newStyle;
this.element.setAttribute('style', newStyle);
}
//Methods
async addClass(className) { this.element.classList.add(className); }
async removeClass(className) { this.element.classList.remove(className); }
hasClass(className) { return this.element.classList.contains(className); }
async appendTo(container) {
container.appendChild(this.element);
await utils.delay(20); //To let the rect being computed
}
async resetStyle() { this.element.setAttribute('style', this.style); }
async modStyle(newStyle) { this.element.setAttribute('style', newStyle); }
}
class ImageWork extends BaseWork {
_container;
constructor(el, container) {
super(el);
this._container = container;
this.newSize();
}
get element() { return this._element; }
get container() { return this._container; }
async newSize() {
this.width = this.container.element.clientHeight > this.container.element.clientWidth ? 'auto' : '100%';
this.height = this.width == 'auto' ? '100%' : 'auto';
this.style = 'width: ' + this.width + '; height: ' + this.height + ';';
}
}
class AnchorWork extends BaseWork {
_position = new Point(0, 0);
_childImage = null;
constructor( el, x = 0, y = 0) {
super(el);
if(x == 0 || y == 0) {
const coord = utils.generateCoord(window.innerWidth, window.innerHeight);
this._position.Set(coord.x, coord.y);
} else this._position.Set(x, y);
this.style = 'left: ' + this.position.x + 'px; top: ' + this.position.y + 'px; display: none; width: ' + this.width + '; height: ' + this.height + ';';
this.generateImage(this.element.querySelector('img'));
setTimeout(() => { this.addClass('work'); }, 200);
}
//Getters - Setters
get element() { return this._element; }
get position() { return this._position; }
get childImage() { return this._childImage; }
set position(newPosition) {
this._position = newPosition;
this.style = 'left: ' + newPosition.x + 'px; top: ' + newPosition.y + 'px; display: none; width: ' + this.width + '; height: ' + this.height + ';';
}
//Methods
generateImage(el) { this._childImage = new ImageWork(el, this); }
async newSize() {
const size = utils.generateSize();
this.width = size.width;
this.height = size.height;
this.style = 'left: ' + this.position.x + 'px; top: ' + this.position.y + 'px; display: none; width: ' + this.width + '; height: ' + this.height + ';';
this.childImage.newSize();
}
}
class Point {
_x;
_y;
constructor(x = 0, y = 0) {
this._x = x;
this._y = y;
}
get x() { return this._x; }
get y() { return this._y; }
set x(newX) { this._x = newX; }
set y(newY) { this._y = newY; }
Set(x, y) {
this.x = x;
this.y = y;
}
}
export { BaseWork, ImageWork, AnchorWork, Point }
Here are some helper functions:
function generateSize() {
const mod = document.body.clientHeight > document.body.clientWidth ? true : false;
const modW = (mod ? 40 : 20);
const modH = (mod ? 20 : 40);
return { width: Math.round((Math.random() * modW) + modW) + '%', height: Math.round((Math.random() * modH) + modH) + '%' }
}
function generateCoord(maxX, maxY) {
let x = Math.round(Math.random() * (maxX ? maxX : window.innerWidth));
let y = Math.round(Math.random() * (maxY ? maxY : window.innerHeight));
return { x: x, y: y };
}
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
export { generateCoord, generateSize, delay }

Related

Letter tracing game with javascript

I want to create game like this. But I have some problem with painting SVG inside canvas. Initially I try to create levels with vanilla js (I use only vuejs), but I got a lot of bugs (I show my code below). After that I try p5js library, but I didn't found how I can fill my SVG with animation. I try to use pixijs, but it so big framework. Also I did not find a solution with createjs library. I'm tired of wasting time looking, can anyone advise me on a framework suitable for my task.
My vanilla code:
new class Game {
constructor() {
this.c = document.querySelector('canvas')
this.cx = this.c.getContext('2d')
this.init()
this.c.addEventListener('mousedown', this.onmousedown, false);
this.c.addEventListener('mouseup', this.onmouseup, false);
this.c.addEventListener('mousemove', this.onmousemove.bind(this), false);
}
init () {
this.c.height = 480;
this.c.width = 320;
this.cx.strokeStyle = 'rgb(0, 0, 50)';
this.drawletter('5');
this.pixels = this.cx.getImageData(0, 0, this.c.width, this.c.height);
this.letterpixels = this.getpixelamount(255, 0, 0);
}
pixelthreshold() {
if (this.getpixelamount(0, 0, 50) / this.letterpixels > 0.35) {
console.log('you got it!');
}
}
showerror(error) {
this.mousedown = false;
console.log(error)
}
getpixelcolour(x, y) {
const index = ((y * (this.pixels.width * 4)) + (x * 4));
return {
r: this.pixels.data[index],
g: this.pixels.data[index + 1],
b: this.pixels.data[index + 2],
a: this.pixels.data[index + 3]
};
}
paint(x, y) {
const colour = this.getpixelcolour(x, y);
if (colour.a === 0) {
this.showerror('you are outside');
} else {
this.cx.beginPath();
if ((this.oldx > 0 && this.oldy > 0) &&
(Math.abs(this.oldx - x) < this.cx.lineWidth / 2 && Math.abs(this.oldy - y) < this.cx.lineWidth / 2)) {
this.cx.moveTo(this.oldx, this.oldy);
}
this.cx.lineTo(x, y);
this.cx.stroke();
this.cx.closePath();
this.oldx = x;
this.oldy = y;
}
}
onmousedown(ev) {
this.mousedown = true;
ev.preventDefault();
}
onmouseup(ev) {
this.mousedown = false;
this.pixelthreshold();
ev.preventDefault();
}
onmousemove(e) {
const x = Math.round(e.clientX - this.c.getBoundingClientRect().left);
const y = Math.round(e.clientY - this.c.getBoundingClientRect().top);
// const x = ev.clientX;
// const y = ev.clientY;
if (this.mousedown) {
this.paint(x, y);
}
}
getpixelamount(r, g, b) {
const pixels = this.cx.getImageData(0, 0, this.c.width, this.c.height);
const all = pixels.data.length;
let amount = 0;
for (let i = 0; i < all; i += 4) {
if (pixels.data[i] === r &&
pixels.data[i + 1] === g &&
pixels.data[i + 2] === b) {
amount++;
}
}
return amount;
}
drawletter(letter) {
const centerx = (this.c.width - this.cx.measureText(letter).width) / 2;
const centery = this.c.height / 2;
// this.cx.fillText(letter, centerx, centery);
// debugger
const path = new Path2D('M60.4248047,180.541992 C73.445638,180.541992 84.9405924,177.693685 94.909668,171.99707 C104.878743,166.300456 112.508138,158.610026 117.797852,148.925781 C123.087565,139.241536 125.732422,128.499349 125.732422,116.699219 C125.732422,108.561198 124.267578,100.952148 121.337891,93.8720703 C118.408203,86.7919922 114.379883,80.6681315 109.25293,75.5004883 C104.125977,70.3328451 98.1648763,66.2841797 91.3696289,63.3544922 C84.5743815,60.4248047 77.2705078,58.9599609 69.4580078,58.9599609 C59.6923828,58.9599609 49.0315755,62.0524089 37.4755859,68.2373047 L37.4755859,68.2373047 L44.4335938,28.6865234 L102.416992,28.6865234 C108.439128,28.6865234 112.996419,27.3844401 116.088867,24.7802734 C119.181315,22.1761068 120.727539,18.758138 120.727539,14.5263672 C120.727539,4.8421224 114.379883,0 101.68457,0 L101.68457,0 L37.2314453,0 C30.2327474,0 25.1871745,1.58691406 22.0947266,4.76074219 C19.0022786,7.93457031 16.8863932,13.0208333 15.7470703,20.0195312 L15.7470703,20.0195312 L5.49316406,78.4912109 C4.59798177,83.6181641 4.15039062,86.3850911 4.15039062,86.7919922 C4.15039062,90.4541016 5.69661458,93.7296549 8.7890625,96.6186523 C11.8815104,99.5076497 15.4215495,100.952148 19.4091797,100.952148 C23.0712891,100.952148 27.730306,98.815918 33.3862305,94.543457 C39.0421549,90.2709961 43.375651,87.2802734 46.3867188,85.5712891 C49.3977865,83.8623047 54.4026693,83.0078125 61.4013672,83.0078125 C67.0979818,83.0078125 72.265625,84.370931 76.9042969,87.097168 C81.5429688,89.8234049 85.2457682,93.9534505 88.0126953,99.4873047 C90.7796224,105.021159 92.1630859,111.694336 92.1630859,119.506836 C92.1630859,126.749674 90.8813477,133.219401 88.3178711,138.916016 C85.7543945,144.61263 82.1126302,149.088542 77.3925781,152.34375 C72.672526,155.598958 67.179362,157.226562 60.9130859,157.226562 C54.0771484,157.226562 47.8922526,155.212402 42.3583984,151.184082 C36.8245443,147.155762 32.430013,141.520182 29.1748047,134.277344 C25.8382161,126.383464 20.7519531,122.436523 13.9160156,122.436523 C9.92838542,122.436523 6.61214193,123.860677 3.96728516,126.708984 C1.32242839,129.557292 0,132.568359 0,135.742188 C0,140.950521 1.89208984,147.033691 5.67626953,153.991699 C9.46044922,160.949707 15.8894857,167.114258 24.9633789,172.485352 C34.0372721,177.856445 45.8577474,180.541992 60.4248047,180.541992 Z');
this.cx.translate(centerx, centery);
this.cx.stroke(path);
}
}
<canvas id=canvas></canvas>
I update my code, not problem insert SVG in canvas. I don't understand how to fill this by touch with animation like in example game.
new class Game {
constructor() {
this.c = document.querySelector('canvas')
this.cx = this.c.getContext('2d')
this.init()
this.c.addEventListener('mousedown', this.onmousedown.bind(this), false);
this.c.addEventListener('mouseup', this.onmouseup.bind(this), false);
this.c.addEventListener('mousemove', this.onmousemove.bind(this), false);
}
init() {
this.c.height = 190;
this.c.width = 140;
this.cx.fillStyle = 'rgb(200, 200, 250)';
this.drawletter('5');
this.cx.fillStyle = 'rgb(0, 0, 50)';
this.letterpixels = this.getpixelamount(200, 200, 250);
}
pixelthreshold() {
if (this.getpixelamount(0, 0, 50) / this.letterpixels > 0.75) {
console.log('you got it!');
}
}
showerror(error) {
this.mousedown = false;
console.log(error)
}
getpixelcolour(x, y) {
const pixels = this.cx.getImageData(0, 0, this.c.width, this.c.height);
const index = ((y * (pixels.width * 4)) + (x * 4));
return {
r: pixels.data[index],
g: pixels.data[index + 1],
b: pixels.data[index + 2],
a: pixels.data[index + 3]
};
}
paint(x, y) {
const colour = this.getpixelcolour(x, y);
if (colour.a === 0) {
this.showerror('you are outside');
} else {
const fillRange = 20;
const stack = [[x, y]];
while (stack.length > 0) {
const pixel = stack.pop();
if (pixel[0] < 0 || pixel[0] >= this.c.width) continue;
if (pixel[1] < 0 || pixel[1] >= this.c.height) continue;
if(((x - pixel[0]) ** 2 + (y - pixel[1]) ** 2) ** .5 > fillRange) continue;
const color = this.getpixelcolour(...pixel);
if (color.a === 0) continue;
if (color.r === 0 && color.g === 0 && color.b === 50) continue;
this.cx.fillRect(pixel[0], pixel[1], 1, 1);
if(pixel[0] >= x) stack.push([pixel[0] + 1, pixel[1]]);
if(pixel[0] <= x) stack.push([pixel[0] - 1, pixel[1]]);
if(pixel[1] >= y) stack.push([pixel[0], pixel[1] + 1]);
if(pixel[1] <= y) stack.push([pixel[0], pixel[1] - 1]);
}
}
}
onmousedown(ev) {
this.mousedown = true;
ev.preventDefault();
}
onmouseup(ev) {
this.mousedown = false;
this.pixelthreshold();
ev.preventDefault();
}
onmousemove(e) {
const x = Math.round(e.clientX - this.c.getBoundingClientRect().left);
const y = Math.round(e.clientY - this.c.getBoundingClientRect().top);
if (this.mousedown) {
this.paint(x, y);
} else {
// console.log(this.getpixelcolour(x, y));
}
}
getpixelamount(r, g, b) {
const pixels = this.cx.getImageData(0, 0, this.c.width, this.c.height);
const all = pixels.data.length;
let amount = 0;
for (let i = 0; i < all; i += 4) {
if (pixels.data[i] === r && pixels.data[i + 1] === g && pixels.data[i + 2] === b) {
amount++;
}
}
return amount;
}
drawletter(letter) {
const path = new Path2D('M60.4248047,180.541992 C73.445638,180.541992 84.9405924,177.693685 94.909668,171.99707 C104.878743,166.300456 112.508138,158.610026 117.797852,148.925781 C123.087565,139.241536 125.732422,128.499349 125.732422,116.699219 C125.732422,108.561198 124.267578,100.952148 121.337891,93.8720703 C118.408203,86.7919922 114.379883,80.6681315 109.25293,75.5004883 C104.125977,70.3328451 98.1648763,66.2841797 91.3696289,63.3544922 C84.5743815,60.4248047 77.2705078,58.9599609 69.4580078,58.9599609 C59.6923828,58.9599609 49.0315755,62.0524089 37.4755859,68.2373047 L37.4755859,68.2373047 L44.4335938,28.6865234 L102.416992,28.6865234 C108.439128,28.6865234 112.996419,27.3844401 116.088867,24.7802734 C119.181315,22.1761068 120.727539,18.758138 120.727539,14.5263672 C120.727539,4.8421224 114.379883,0 101.68457,0 L101.68457,0 L37.2314453,0 C30.2327474,0 25.1871745,1.58691406 22.0947266,4.76074219 C19.0022786,7.93457031 16.8863932,13.0208333 15.7470703,20.0195312 L15.7470703,20.0195312 L5.49316406,78.4912109 C4.59798177,83.6181641 4.15039062,86.3850911 4.15039062,86.7919922 C4.15039062,90.4541016 5.69661458,93.7296549 8.7890625,96.6186523 C11.8815104,99.5076497 15.4215495,100.952148 19.4091797,100.952148 C23.0712891,100.952148 27.730306,98.815918 33.3862305,94.543457 C39.0421549,90.2709961 43.375651,87.2802734 46.3867188,85.5712891 C49.3977865,83.8623047 54.4026693,83.0078125 61.4013672,83.0078125 C67.0979818,83.0078125 72.265625,84.370931 76.9042969,87.097168 C81.5429688,89.8234049 85.2457682,93.9534505 88.0126953,99.4873047 C90.7796224,105.021159 92.1630859,111.694336 92.1630859,119.506836 C92.1630859,126.749674 90.8813477,133.219401 88.3178711,138.916016 C85.7543945,144.61263 82.1126302,149.088542 77.3925781,152.34375 C72.672526,155.598958 67.179362,157.226562 60.9130859,157.226562 C54.0771484,157.226562 47.8922526,155.212402 42.3583984,151.184082 C36.8245443,147.155762 32.430013,141.520182 29.1748047,134.277344 C25.8382161,126.383464 20.7519531,122.436523 13.9160156,122.436523 C9.92838542,122.436523 6.61214193,123.860677 3.96728516,126.708984 C1.32242839,129.557292 0,132.568359 0,135.742188 C0,140.950521 1.89208984,147.033691 5.67626953,153.991699 C9.46044922,160.949707 15.8894857,167.114258 24.9633789,172.485352 C34.0372721,177.856445 45.8577474,180.541992 60.4248047,180.541992 Z');
this.cx.fill(path);
}
}
<canvas id=canvas></canvas>
const ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 300;
const svg = new Image();
svg.onload = () => ctx.drawImage(svg, 0, 0);
svg.src = "http://graphing.ru/examples/butterfly.svg";
<canvas id=canvas></canvas>

Two signature pads in one form

I want to implement two signature pads in ONE form. One signature is for the applicant and the other one is for the evaluator.
The first pad works but the second pad is unresponsive. I am using JavaScript for the signature pads but it only works for the first pad. The signature will be saved to the database when the submit button is clicked. That is why id="save-signature-btn" is together with the code for the 'Submit' button.
form.blade.php
#extends('layouts.app')
#section('content')
<!doctype html>
<html lang="en">
<head>
</head>
<body>
{!! Form::open(['url' => 'page3/submit']) !!}
<h4 style="text-decoration: underline; font-weight: bold">Approved By:</h4>
<table class="table table-bordered">
<tr>
<th colspan="3">Approved By:</th>
</tr>
<tr>
<th colspan="1">Name</th>
<th colspan="1">Signature</th>
<th colspan="1">Date</th>
</tr>
<tr colspan=4>
<td colspan="1">
<div class="form-group">
{{Form::text('Officer_Name', '', ['class' => 'form-control', 'placeholder' => 'John Smith'])}}
</div>
</td>
<td colspan="1">
<div class="form-group">
<canvas id="signature-canvas" style="width:375px;height:150px;max-width:100%;border:8px #CCC solid;background-color: white;"></canvas>
<div id="signature-message"></div>
<div id="signature-buttons">
<input type="button" id="clear-signature-btn" value="Clear">
</div>
<input type="hidden" name="officer_signature" id="signature-data" value="">
</div>
</td>
<td>
<div class="form-group">
{{Form::date('Approval_Date', '', ['class' => 'form-control'])}}
</div>
</td>
</tr>
</table>
<br/>
<h4 style="text-decoration: underline; font-weight: bold">Applicant Signature:</h4>
<div class="form-group">
<canvas id="signature-canvas2" style="width:375px;height:150px;max-width:100%;border:8px #CCC solid;background-color: white;"></canvas>
<div id="signature-message2"></div>
<div id="signature-buttons2">
<input type="button" id="clear-signature-btn2" value="Clear">
</div>
<input type="hidden" name="applicant_signature" id="signature-data2" value="">
</div>
<br>
<div class="signature_pad_save">
<button type="submit" class="btn btn-primary" id="save-signature-btn">Submit</button>
</div>
<script src="js/signature_pad.js"></script>
<script src="js/signature_data.js"></script>
</body>
</html>
#endsection('content')
signature data.js
var clearButton = document.getElementById('clear-signature-btn'),
saveButton = document.getElementById('save-signature-btn'),
canvas = document.getElementById('signature-canvas'),
signaturePad;
function resizeCanvas() {
var ratio = Math.max(window.devicePixelRatio || 1, 1);
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
canvas.getContext("2d").scale(ratio, ratio);
}
window.onresize = resizeCanvas;
resizeCanvas();
signaturePad = new SignaturePad(canvas);
clearButton.addEventListener('click', function (event) {
signaturePad.clear();
});
saveButton.addEventListener('click', function (event) {
if (signaturePad.isEmpty()) {
alert('Signature pad is blank. Please draw your signature.');
} else {
var sdata = signaturePad.toDataURL();
document.getElementById('signature-data').value = sdata;
document.getElementById('signature-form').submit();
}
});
signature pad.js
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.SignaturePad = factory());
}(this, (function () { 'use strict';
function Point(x, y, time) {
this.x = x;
this.y = y;
this.time = time || new Date().getTime();
}
Point.prototype.velocityFrom = function (start) {
return this.time !== start.time ? this.distanceTo(start) / (this.time - start.time) : 1;
};
Point.prototype.distanceTo = function (start) {
return Math.sqrt(Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2));
};
Point.prototype.equals = function (other) {
return this.x === other.x && this.y === other.y && this.time === other.time;
};
function Bezier(startPoint, control1, control2, endPoint) {
this.startPoint = startPoint;
this.control1 = control1;
this.control2 = control2;
this.endPoint = endPoint;
}
// Returns approximated length.
Bezier.prototype.length = function () {
var steps = 10;
var length = 0;
var px = void 0;
var py = void 0;
for (var i = 0; i <= steps; i += 1) {
var t = i / steps;
var cx = this._point(t, this.startPoint.x, this.control1.x, this.control2.x, this.endPoint.x);
var cy = this._point(t, this.startPoint.y, this.control1.y, this.control2.y, this.endPoint.y);
if (i > 0) {
var xdiff = cx - px;
var ydiff = cy - py;
length += Math.sqrt(xdiff * xdiff + ydiff * ydiff);
}
px = cx;
py = cy;
}
return length;
};
/* eslint-disable no-multi-spaces, space-in-parens */
Bezier.prototype._point = function (t, start, c1, c2, end) {
return start * (1.0 - t) * (1.0 - t) * (1.0 - t) + 3.0 * c1 * (1.0 - t) * (1.0 - t) * t + 3.0 * c2 * (1.0 - t) * t * t + end * t * t * t;
};
/* eslint-disable */
// http://stackoverflow.com/a/27078401/815507
function throttle(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function later() {
previous = options.leading === false ? 0 : Date.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function () {
var now = Date.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
}
function SignaturePad(canvas, options) {
var self = this;
var opts = options || {};
this.velocityFilterWeight = opts.velocityFilterWeight || 0.7;
this.minWidth = opts.minWidth || 0.5;
this.maxWidth = opts.maxWidth || 2.5;
this.throttle = 'throttle' in opts ? opts.throttle : 16; // in miliseconds
this.minDistance = 'minDistance' in opts ? opts.minDistance : 5;
if (this.throttle) {
this._strokeMoveUpdate = throttle(SignaturePad.prototype._strokeUpdate, this.throttle);
} else {
this._strokeMoveUpdate = SignaturePad.prototype._strokeUpdate;
}
this.dotSize = opts.dotSize || function () {
return (this.minWidth + this.maxWidth) / 2;
};
this.penColor = opts.penColor || 'black';
this.backgroundColor = opts.backgroundColor || 'rgba(0,0,0,0)';
this.onBegin = opts.onBegin;
this.onEnd = opts.onEnd;
this._canvas = canvas;
this._ctx = canvas.getContext('2d');
this.clear();
// We need add these inline so they are available to unbind while still having
// access to 'self' we could use _.bind but it's not worth adding a dependency.
this._handleMouseDown = function (event) {
if (event.which === 1) {
self._mouseButtonDown = true;
self._strokeBegin(event);
}
};
this._handleMouseMove = function (event) {
if (self._mouseButtonDown) {
self._strokeMoveUpdate(event);
}
};
this._handleMouseUp = function (event) {
if (event.which === 1 && self._mouseButtonDown) {
self._mouseButtonDown = false;
self._strokeEnd(event);
}
};
this._handleTouchStart = function (event) {
if (event.targetTouches.length === 1) {
var touch = event.changedTouches[0];
self._strokeBegin(touch);
}
};
this._handleTouchMove = function (event) {
// Prevent scrolling.
event.preventDefault();
var touch = event.targetTouches[0];
self._strokeMoveUpdate(touch);
};
this._handleTouchEnd = function (event) {
var wasCanvasTouched = event.target === self._canvas;
if (wasCanvasTouched) {
event.preventDefault();
self._strokeEnd(event);
}
};
// Enable mouse and touch event handlers
this.on();
}
// Public methods
SignaturePad.prototype.clear = function () {
var ctx = this._ctx;
var canvas = this._canvas;
ctx.fillStyle = this.backgroundColor;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(0, 0, canvas.width, canvas.height);
this._data = [];
this._reset();
this._isEmpty = true;
};
SignaturePad.prototype.fromDataURL = function (dataUrl) {
var _this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var image = new Image();
var ratio = options.ratio || window.devicePixelRatio || 1;
var width = options.width || this._canvas.width / ratio;
var height = options.height || this._canvas.height / ratio;
this._reset();
image.src = dataUrl;
image.onload = function () {
_this._ctx.drawImage(image, 0, 0, width, height);
};
this._isEmpty = false;
};
SignaturePad.prototype.toDataURL = function (type) {
var _canvas;
switch (type) {
case 'image/svg+xml':
return this._toSVG();
default:
for (var _len = arguments.length, options = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
options[_key - 1] = arguments[_key];
}
return (_canvas = this._canvas).toDataURL.apply(_canvas, [type].concat(options));
}
};
SignaturePad.prototype.on = function () {
this._handleMouseEvents();
this._handleTouchEvents();
};
SignaturePad.prototype.off = function () {
this._canvas.removeEventListener('mousedown', this._handleMouseDown);
this._canvas.removeEventListener('mousemove', this._handleMouseMove);
document.removeEventListener('mouseup', this._handleMouseUp);
this._canvas.removeEventListener('touchstart', this._handleTouchStart);
this._canvas.removeEventListener('touchmove', this._handleTouchMove);
this._canvas.removeEventListener('touchend', this._handleTouchEnd);
};
SignaturePad.prototype.isEmpty = function () {
return this._isEmpty;
};
// Private methods
SignaturePad.prototype._strokeBegin = function (event) {
this._data.push([]);
this._reset();
this._strokeUpdate(event);
if (typeof this.onBegin === 'function') {
this.onBegin(event);
}
};
SignaturePad.prototype._strokeUpdate = function (event) {
var x = event.clientX;
var y = event.clientY;
var point = this._createPoint(x, y);
var lastPointGroup = this._data[this._data.length - 1];
var lastPoint = lastPointGroup && lastPointGroup[lastPointGroup.length - 1];
var isLastPointTooClose = lastPoint && point.distanceTo(lastPoint) < this.minDistance;
// Skip this point if it's too close to the previous one
if (!(lastPoint && isLastPointTooClose)) {
var _addPoint = this._addPoint(point),
curve = _addPoint.curve,
widths = _addPoint.widths;
if (curve && widths) {
this._drawCurve(curve, widths.start, widths.end);
}
this._data[this._data.length - 1].push({
x: point.x,
y: point.y,
time: point.time,
color: this.penColor
});
}
};
SignaturePad.prototype._strokeEnd = function (event) {
var canDrawCurve = this.points.length > 2;
var point = this.points[0]; // Point instance
if (!canDrawCurve && point) {
this._drawDot(point);
}
if (point) {
var lastPointGroup = this._data[this._data.length - 1];
var lastPoint = lastPointGroup[lastPointGroup.length - 1]; // plain object
// When drawing a dot, there's only one point in a group, so without this check
// such group would end up with exactly the same 2 points.
if (!point.equals(lastPoint)) {
lastPointGroup.push({
x: point.x,
y: point.y,
time: point.time,
color: this.penColor
});
}
}
if (typeof this.onEnd === 'function') {
this.onEnd(event);
}
};
SignaturePad.prototype._handleMouseEvents = function () {
this._mouseButtonDown = false;
this._canvas.addEventListener('mousedown', this._handleMouseDown);
this._canvas.addEventListener('mousemove', this._handleMouseMove);
document.addEventListener('mouseup', this._handleMouseUp);
};
SignaturePad.prototype._handleTouchEvents = function () {
// Pass touch events to canvas element on mobile IE11 and Edge.
this._canvas.style.msTouchAction = 'none';
this._canvas.style.touchAction = 'none';
this._canvas.addEventListener('touchstart', this._handleTouchStart);
this._canvas.addEventListener('touchmove', this._handleTouchMove);
this._canvas.addEventListener('touchend', this._handleTouchEnd);
};
SignaturePad.prototype._reset = function () {
this.points = [];
this._lastVelocity = 0;
this._lastWidth = (this.minWidth + this.maxWidth) / 2;
this._ctx.fillStyle = this.penColor;
};
SignaturePad.prototype._createPoint = function (x, y, time) {
var rect = this._canvas.getBoundingClientRect();
return new Point(x - rect.left, y - rect.top, time || new Date().getTime());
};
SignaturePad.prototype._addPoint = function (point) {
var points = this.points;
var tmp = void 0;
points.push(point);
if (points.length > 2) {
// To reduce the initial lag make it work with 3 points
// by copying the first point to the beginning.
if (points.length === 3) points.unshift(points[0]);
tmp = this._calculateCurveControlPoints(points[0], points[1], points[2]);
var c2 = tmp.c2;
tmp = this._calculateCurveControlPoints(points[1], points[2], points[3]);
var c3 = tmp.c1;
var curve = new Bezier(points[1], c2, c3, points[2]);
var widths = this._calculateCurveWidths(curve);
// Remove the first element from the list,
// so that we always have no more than 4 points in points array.
points.shift();
return { curve: curve, widths: widths };
}
return {};
};
SignaturePad.prototype._calculateCurveControlPoints = function (s1, s2, s3) {
var dx1 = s1.x - s2.x;
var dy1 = s1.y - s2.y;
var dx2 = s2.x - s3.x;
var dy2 = s2.y - s3.y;
var m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };
var m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };
var l1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);
var l2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);
var dxm = m1.x - m2.x;
var dym = m1.y - m2.y;
var k = l2 / (l1 + l2);
var cm = { x: m2.x + dxm * k, y: m2.y + dym * k };
var tx = s2.x - cm.x;
var ty = s2.y - cm.y;
return {
c1: new Point(m1.x + tx, m1.y + ty),
c2: new Point(m2.x + tx, m2.y + ty)
};
};
SignaturePad.prototype._calculateCurveWidths = function (curve) {
var startPoint = curve.startPoint;
var endPoint = curve.endPoint;
var widths = { start: null, end: null };
var velocity = this.velocityFilterWeight * endPoint.velocityFrom(startPoint) + (1 - this.velocityFilterWeight) * this._lastVelocity;
var newWidth = this._strokeWidth(velocity);
widths.start = this._lastWidth;
widths.end = newWidth;
this._lastVelocity = velocity;
this._lastWidth = newWidth;
return widths;
};
SignaturePad.prototype._strokeWidth = function (velocity) {
return Math.max(this.maxWidth / (velocity + 1), this.minWidth);
};
SignaturePad.prototype._drawPoint = function (x, y, size) {
var ctx = this._ctx;
ctx.moveTo(x, y);
ctx.arc(x, y, size, 0, 2 * Math.PI, false);
this._isEmpty = false;
};
SignaturePad.prototype._drawCurve = function (curve, startWidth, endWidth) {
var ctx = this._ctx;
var widthDelta = endWidth - startWidth;
var drawSteps = Math.floor(curve.length());
ctx.beginPath();
for (var i = 0; i < drawSteps; i += 1) {
// Calculate the Bezier (x, y) coordinate for this step.
var t = i / drawSteps;
var tt = t * t;
var ttt = tt * t;
var u = 1 - t;
var uu = u * u;
var uuu = uu * u;
var x = uuu * curve.startPoint.x;
x += 3 * uu * t * curve.control1.x;
x += 3 * u * tt * curve.control2.x;
x += ttt * curve.endPoint.x;
var y = uuu * curve.startPoint.y;
y += 3 * uu * t * curve.control1.y;
y += 3 * u * tt * curve.control2.y;
y += ttt * curve.endPoint.y;
var width = startWidth + ttt * widthDelta;
this._drawPoint(x, y, width);
}
ctx.closePath();
ctx.fill();
};
SignaturePad.prototype._drawDot = function (point) {
var ctx = this._ctx;
var width = typeof this.dotSize === 'function' ? this.dotSize() : this.dotSize;
ctx.beginPath();
this._drawPoint(point.x, point.y, width);
ctx.closePath();
ctx.fill();
};
SignaturePad.prototype._fromData = function (pointGroups, drawCurve, drawDot) {
for (var i = 0; i < pointGroups.length; i += 1) {
var group = pointGroups[i];
if (group.length > 1) {
for (var j = 0; j < group.length; j += 1) {
var rawPoint = group[j];
var point = new Point(rawPoint.x, rawPoint.y, rawPoint.time);
var color = rawPoint.color;
if (j === 0) {
// First point in a group. Nothing to draw yet.
// All points in the group have the same color, so it's enough to set
// penColor just at the beginning.
this.penColor = color;
this._reset();
this._addPoint(point);
} else if (j !== group.length - 1) {
// Middle point in a group.
var _addPoint2 = this._addPoint(point),
curve = _addPoint2.curve,
widths = _addPoint2.widths;
if (curve && widths) {
drawCurve(curve, widths, color);
}
} else {
// Last point in a group. Do nothing.
}
}
} else {
this._reset();
var _rawPoint = group[0];
drawDot(_rawPoint);
}
}
};
SignaturePad.prototype._toSVG = function () {
var _this2 = this;
var pointGroups = this._data;
var canvas = this._canvas;
var ratio = Math.max(window.devicePixelRatio || 1, 1);
var minX = 0;
var minY = 0;
var maxX = canvas.width / ratio;
var maxY = canvas.height / ratio;
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttributeNS(null, 'width', canvas.width);
svg.setAttributeNS(null, 'height', canvas.height);
this._fromData(pointGroups, function (curve, widths, color) {
var path = document.createElement('path');
// Need to check curve for NaN values, these pop up when drawing
// lines on the canvas that are not continuous. E.g. Sharp corners
// or stopping mid-stroke and than continuing without lifting mouse.
if (!isNaN(curve.control1.x) && !isNaN(curve.control1.y) && !isNaN(curve.control2.x) && !isNaN(curve.control2.y)) {
var attr = 'M ' + curve.startPoint.x.toFixed(3) + ',' + curve.startPoint.y.toFixed(3) + ' ' + ('C ' + curve.control1.x.toFixed(3) + ',' + curve.control1.y.toFixed(3) + ' ') + (curve.control2.x.toFixed(3) + ',' + curve.control2.y.toFixed(3) + ' ') + (curve.endPoint.x.toFixed(3) + ',' + curve.endPoint.y.toFixed(3));
path.setAttribute('d', attr);
path.setAttribute('stroke-width', (widths.end * 2.25).toFixed(3));
path.setAttribute('stroke', color);
path.setAttribute('fill', 'none');
path.setAttribute('stroke-linecap', 'round');
svg.appendChild(path);
}
}, function (rawPoint) {
var circle = document.createElement('circle');
var dotSize = typeof _this2.dotSize === 'function' ? _this2.dotSize() : _this2.dotSize;
circle.setAttribute('r', dotSize);
circle.setAttribute('cx', rawPoint.x);
circle.setAttribute('cy', rawPoint.y);
circle.setAttribute('fill', rawPoint.color);
svg.appendChild(circle);
});
var prefix = 'data:image/svg+xml;base64,';
var header = '<svg' + ' xmlns="http://www.w3.org/2000/svg"' + ' xmlns:xlink="http://www.w3.org/1999/xlink"' + (' viewBox="' + minX + ' ' + minY + ' ' + maxX + ' ' + maxY + '"') + (' width="' + maxX + '"') + (' height="' + maxY + '"') + '>';
var body = svg.innerHTML;
// IE hack for missing innerHTML property on SVGElement
if (body === undefined) {
var dummy = document.createElement('dummy');
var nodes = svg.childNodes;
dummy.innerHTML = '';
for (var i = 0; i < nodes.length; i += 1) {
dummy.appendChild(nodes[i].cloneNode(true));
}
body = dummy.innerHTML;
}
var footer = '</svg>';
var data = header + body + footer;
return prefix + btoa(data);
};
SignaturePad.prototype.fromData = function (pointGroups) {
var _this3 = this;
this.clear();
this._fromData(pointGroups, function (curve, widths) {
return _this3._drawCurve(curve, widths.start, widths.end);
}, function (rawPoint) {
return _this3._drawDot(rawPoint);
});
this._data = pointGroups;
};
SignaturePad.prototype.toData = function () {
return this._data;
};
return SignaturePad;
})));
In your javascript code you are working only with
canvas = document.getElementById('signature-canvas')
So that is the problem.
You should add a class on both signature canvases in html code for example signature like this:
<canvas id="signature-canvas" class="signature" style="width:375px;height:150px;max-width:100%;border:8px #CCC solid;background-color: white;"></canvas>
<canvas id="signature-canvas2" class="signature" style="width:375px;height:150px;max-width:100%;border:8px #CCC solid;background-color: white;"></canvas>
And then in javascript add one more pair of commands for second signature pad for control buttons (submit and reset) for second canvas.

Sometimes white background goes transparent on whole page

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>

Jquery stopped working

I'm developping this mobile app and I'm usint this (https://github.com/krisrak/appframework-templates/blob/master/template-CarouselViewApp.html) as a carousel to change through content on a page. http://jsfiddle.net/nafis56/qCkqb/
So for this I need to mess around in HTML, CSS and Jquery. Unfortonetly I'm still very green at javascript so I need your help. I changed an ID to a Class because I need to call it more than once in the same page. In the original template I refeered to, it comes as an ID. So I did this to change it:
Changed matching code on html to call it as a Class.
<div class="panel" title="Desiree Charms" id="desiree_charms" style="overflow: hidden;"
data-appbuilder-object="page">
<div class="carousel">
<div class="carousel_page">
<h2>Desiree Charms</h2>
<p><img src="images/desiree_charms.jpg" style="width: 85%; height: 85%; display: block; margin-left: auto; margin-right: auto "
data-appbuilder-object="image" class="" title="">
</p>
</div>
<div class="carousel_page">
<h2>Page Two</h2>
<p>Text and images for Page Two goes here. Swipe to go to the
next page.</p>
</div>
</div>
<div class="carousel_dots"></div>
</div>
also this on the html.
<script>
$.ui.autoLaunch = false;
$.ui.animateHeaders = false;
$(document).ready(function(){
$.ui.launch();
});
$.ui.ready(function(){
carouselSetup();
});
function carouselSetup(){
// set size of carousel
$(".carousel").width($(".carousel").closest(".panel").width());
$(".carousel").height($(".carousel").closest(".panel").height()-25);
var options={
vertical:false, // page up/down
horizontal:true, // page left/right
pagingDiv:"carousel_dots", // div to hold the dots for paging
pagingCssName:"carousel_paging", //classname for the paging dots
pagingCssNameSelected: "carousel_paging_selected", //classname for the selected page dots
wrap:true //Creates a continuous carousel
}
var carousel = $(".carousel").carousel(options);
}
Changed # to . on Css.
.carousel {
overflow:hidden;
margin:0 -10px;
}
.carousel_page {
overflow: auto;
-webkit-scrolling:touch;
padding:0 10px;
}
.carousel_dots {
text-align: center;
margin-left: auto;
margin-right: auto;
clear: both;
position:relative;
top:0;
z-index:200;
}
.carousel_paging {
border-radius: 10px;
background: #ccc;
width: 10px;
height: 10px;
display:inline-block;
}
.carousel_paging_selected {
border-radius: 10px;
background: #000;
width: 10px;
height: 10px;
display:inline-block;
}
.carousel h2 {
text-align: center;
}
This is the jquery ( I didn't change anything)
/**
* af.web.carousel - a carousel library for App Framework apps
* #copyright 2011 - Intel
*
*/
(function($) {
var cache = [];
var objId=function(obj){
if(!obj.afmCarouselId) obj.afmCarouselId=$.uuid();
return obj.afmCarouselId;
}
$.fn.carousel = function(opts) {
var tmp, id;
for (var i = 0; i < this.length; i++) {
//cache system
id = objId(this[i]);
if(!cache[id]){
tmp = new carousel(this[i], opts);
cache[id] = tmp;
} else {
tmp = cache[id];
}
}
return this.length == 1 ? tmp : this;
};
var carousel = (function() {
var translateOpen =$.feat.cssTransformStart;
var translateClose = $.feat.cssTransformEnd;
var carousel = function(containerEl, opts) {
if (typeof containerEl === "string" || containerEl instanceof String) {
this.container = document.getElementById(containerEl);
} else {
this.container = containerEl;
}
if (!this.container) {
alert("Error finding container for carousel " + containerEl);
return;
}
if (this instanceof carousel) {
for (var j in opts) {
if (opts.hasOwnProperty(j)) {
this[j] = opts[j];
}
}
} else {
return new carousel(containerEl, opts);
}
var that = this;
af(this.container).bind('destroy', function(e){
var id = that.container.afmCarouselId;
//window event need to be cleaned up manually, remaining binds are automatically killed in the dom cleanup process
window.removeEventListener("orientationchange", that.orientationHandler, false);
if(cache[id]) delete cache[id];
e.stopPropagation();
});
this.pagingDiv = this.pagingDiv ? document.getElementById(this.pagingDiv) : null;
// initial setup
this.container.style.overflow = "hidden";
if (this.vertical) {
this.horizontal = false;
}
var el = document.createElement("div");
this.container.appendChild(el);
var $el=$(el);
var $container=$(this.container);
var data = Array.prototype.slice.call(this.container.childNodes);
while(data.length>0)
{
var myEl=data.splice(0,1);
myEl=$container.find(myEl);
if(myEl.get(0)==el)
continue;
$el.append(myEl.get(0));
}
if (this.horizontal) {
el.style.display = "block";
el.style['float']="left";
}
else {
el.style.display = "block";
}
this.el = el;
this.refreshItems();
var afEl = af(el);
afEl.bind('touchmove', function(e) {that.touchMove(e);});
afEl.bind('touchend', function(e) {that.touchEnd(e);});
afEl.bind('touchstart', function(e) {that.touchStart(e);});
this.orientationHandler = function() {that.onMoveIndex(that.carouselIndex,0);};
window.addEventListener("orientationchange", this.orientationHandler, false);
};
carousel.prototype = {
wrap:true,
startX: 0,
startY: 0,
dx: 0,
dy: 0,
glue: false,
myDivWidth: 0,
myDivHeight: 0,
cssMoveStart: 0,
childrenCount: 0,
carouselIndex: 0,
vertical: false,
horizontal: true,
el: null,
movingElement: false,
container: null,
pagingDiv: null,
pagingCssName: "carousel_paging",
pagingCssNameSelected: "carousel_paging_selected",
pagingFunction: null,
lockMove:false,
okToMove: false,
// handle the moving function
touchStart: function(e) {
this.okToMove = false;
this.myDivWidth = numOnly(this.container.clientWidth);
this.myDivHeight = numOnly(this.container.clientHeight);
this.lockMove=false;
if (e.touches[0].target && e.touches[0].target.type !== undefined) {
var tagname = e.touches[0].target.tagName.toLowerCase();
if (tagname === "select" || tagname === "input" || tagname === "button") // stuff we need to allow
{
return;
}
}
if (e.touches.length === 1) {
this.movingElement = true;
this.startY = e.touches[0].pageY;
this.startX = e.touches[0].pageX;
var cssMatrix=$.getCssMatrix(this.el);
if (this.vertical) {
try {
this.cssMoveStart = numOnly(cssMatrix.f);
} catch (ex1) {
this.cssMoveStart = 0;
}
} else {
try {
this.cssMoveStart = numOnly(cssMatrix.e);
} catch (ex1) {
this.cssMoveStart = 0;
}
}
}
},
touchMove: function(e) {
if(!this.movingElement)
return;
if (e.touches.length > 1) {
return this.touchEnd(e);
}
var rawDelta = {
x: e.touches[0].pageX - this.startX,
y: e.touches[0].pageY - this.startY
};
if (this.vertical) {
var movePos = { x: 0, y: 0 };
this.dy = e.touches[0].pageY - this.startY;
this.dy += this.cssMoveStart;
movePos.y = this.dy;
e.preventDefault();
//e.stopPropagation();
} else {
if ((!this.lockMove&&isHorizontalSwipe(rawDelta.x, rawDelta.y))||Math.abs(this.dx)>5) {
var movePos = {x: 0,y: 0};
this.dx = e.touches[0].pageX - this.startX;
this.dx += this.cssMoveStart;
e.preventDefault();
// e.stopPropagation();
movePos.x = this.dx;
}
else
return this.lockMove=true;
}
var totalMoved = this.vertical ? ((this.dy % this.myDivHeight) / this.myDivHeight * 100) * -1 : ((this.dx % this.myDivWidth) / this.myDivWidth * 100) * -1; // get a percentage of movement.
if (!this.okToMove) {
oldStateOkToMove= this.okToMove;
this.okToMove = this.glue ? Math.abs(totalMoved) > this.glue && Math.abs(totalMoved) < (100 - this.glue) : true;
if (this.okToMove && !oldStateOkToMove) {
$.trigger(this,"movestart",[this.el]);
}
}
if (this.okToMove && movePos)
this.moveCSS3(this.el, movePos);
},
touchEnd: function(e) {
if (!this.movingElement) {
return;
}
$.trigger(this,"movestop",[this.el]);
// e.preventDefault();
// e.stopPropagation();
var runFinal = false;
// try {
var cssMatrix=$.getCssMatrix(this.el);
var endPos = this.vertical ? numOnly(cssMatrix.f) : numOnly(cssMatrix.e);
if (1==2&&endPos > 0) {
this.moveCSS3(this.el, {
x: 0,
y: 0
}, "300");
} else {
var totalMoved = this.vertical ? ((this.dy % this.myDivHeight) / this.myDivHeight * 100) * -1 : ((this.dx % this.myDivWidth) / this.myDivWidth * 100) * -1; // get a percentage of movement.
// Only need
// to drag 3% to trigger an event
var currInd = this.carouselIndex;
if (endPos < this.cssMoveStart && totalMoved > 3) {
currInd++; // move right/down
} else if ((endPos > this.cssMoveStart && totalMoved < 97)) {
currInd--; // move left/up
}
var toMove=currInd;
//Checks for infinite - moves to placeholders
if(this.wrap){
if (currInd > (this.childrenCount - 1)) {
currInd = 0;
toMove=this.childrenCount;
}
if (currInd < 0) {
currInd = this.childrenCount-1;
toMove=-1;
}
}
else {
if(currInd<0)
currInd=0;
if(currInd>this.childrenCount-1)
currInd=this.childrenCount-1;
toMove=currInd;
}
var movePos = {
x: 0,
y: 0
};
if (this.vertical) {
movePos.y = (toMove * this.myDivHeight * -1);
}
else {
movePos.x = (toMove * this.myDivWidth * -1);
}
this.moveCSS3(this.el, movePos, "150");
if (this.pagingDiv && this.carouselIndex !== currInd) {
document.getElementById(this.container.id + "_" + this.carouselIndex).className = this.pagingCssName;
document.getElementById(this.container.id + "_" + currInd).className = this.pagingCssNameSelected;
}
if (this.carouselIndex != currInd)
runFinal = true;
this.carouselIndex = currInd;
//This is for the infinite ends - will move to the correct position after animation
if(this.wrap){
if(toMove!=currInd){
var that=this;
window.setTimeout(function(){
that.onMoveIndex(currInd,"1ms");
},155);
}
}
}
//} catch (e) {
// console.log(e);
// }
this.dx = 0;
this.movingElement = false;
this.startX = 0;
this.dy = 0;
this.startY = 0;
if (runFinal && this.pagingFunction && typeof this.pagingFunction == "function")
this.pagingFunction(this.carouselIndex);
},
onMoveIndex: function(newInd,transitionTime) {
this.myDivWidth = numOnly(this.container.clientWidth);
this.myDivHeight = numOnly(this.container.clientHeight);
var runFinal = false;
if(document.getElementById(this.container.id + "_" + this.carouselIndex))
document.getElementById(this.container.id + "_" + this.carouselIndex).className = this.pagingCssName;
var newTime = Math.abs(newInd - this.carouselIndex);
var ind = newInd;
if (ind < 0)
ind = 0;
if (ind > this.childrenCount - 1) {
ind = this.childrenCount - 1;
}
var movePos = {
x: 0,
y: 0
};
if (this.vertical) {
movePos.y = (ind * this.myDivHeight * -1);
}
else {
movePos.x = (ind * this.myDivWidth * -1);
}
var time =transitionTime?transitionTime: 50 + parseInt((newTime * 20));
this.moveCSS3(this.el, movePos, time);
if (this.carouselIndex != ind)
runFinal = true;
this.carouselIndex = ind;
if (this.pagingDiv) {
var tmpEl = document.getElementById(this.container.id + "_" + this.carouselIndex);
if(tmpEl) tmpEl.className = this.pagingCssNameSelected;
}
if (runFinal && this.pagingFunction && typeof this.pagingFunction == "function")
this.pagingFunction(currInd);
},
moveCSS3: function(el, distanceToMove, time, timingFunction) {
if (!time)
time = 0;
else
time = parseInt(time);
if (!timingFunction)
timingFunction = "linear";
el.style[$.feat.cssPrefix+"Transform"] = "translate" + translateOpen + distanceToMove.x + "px," + distanceToMove.y + "px" + translateClose;
el.style[$.feat.cssPrefix+"TransitionDuration"] = time + "ms";
el.style[$.feat.cssPrefix+"BackfaceVisibility"] = "hidden";
el.style[$.feat.cssPrefix+"TransitionTimingFunction"] = timingFunction;
},
addItem: function(el) {
if (el && el.nodeType) {
this.container.childNodes[0].appendChild(el);
this.refreshItems();
}
},
refreshItems: function() {
var childrenCounter = 0;
var that = this;
var el = this.el;
$(el).children().find(".prevBuffer").remove();
$(el).children().find(".nextBuffer").remove();
n = el.childNodes[0];
var widthParam;
var heightParam = "100%";
var elems = [];
for (; n; n = n.nextSibling) {
if (n.nodeType === 1) {
elems.push(n);
childrenCounter++;
}
}
//Let's put the buffers at the start/end
if(this.wrap){
var prep=$(elems[elems.length-1]).clone().get(0);
$(el).prepend(prep);
var tmp=$(elems[0]).clone().get(0);
$(el).append(tmp);
elems.push(tmp);
elems.unshift(prep);
tmp.style.position="absolute";
prep.style.position="absolute";
}
var param = (100 / childrenCounter) + "%";
this.childrenCount = childrenCounter;
widthParam = parseFloat(100 / childrenCounter) + "%";
for (var i = 0; i < elems.length; i++) {
if (this.horizontal) {
elems[i].style.width = widthParam;
elems[i].style.height = "100%";
elems[i].style['float']="left";
}
else {
elems[i].style.height = widthParam;
elems[i].style.width = "100%";
elems[i].style.display = "block";
}
}
//Clone the first and put it at the end
this.moveCSS3(el, {
x: 0,
y: 0
});
if (this.horizontal) {
el.style.width = Math.ceil((this.childrenCount) * 100) + "%";
el.style.height = "100%";
el.style['min-height'] = "100%"
if(this.wrap){
prep.style.left="-"+widthParam;
tmp.style.left="100%";
}
}
else {
el.style.width = "100%";
el.style.height = Math.ceil((this.childrenCount) * 100) + "%";
el.style['min-height'] = Math.ceil((this.childrenCount) * 100) + "%";
if(this.wrap){
prep.style.top="-"+widthParam;
tmp.style.top="100%";
}
}
// Create the paging dots
if (this.pagingDiv) {
this.pagingDiv.innerHTML = ""
for (i = 0; i < this.childrenCount; i++) {
var pagingEl = document.createElement("div");
pagingEl.id = this.container.id + "_" + i;
pagingEl.pageId = i;
if (i !== this.carouselIndex) {
pagingEl.className = this.pagingCssName;
}
else {
pagingEl.className = this.pagingCssNameSelected;
}
pagingEl.onclick = function() {
that.onMoveIndex(this.pageId);
};
var spacerEl = document.createElement("div");
spacerEl.style.width = "20px";
if(this.horizontal){
spacerEl.style.display = "inline-block";
spacerEl.innerHTML = " ";
}
else{
spacerEl.innerHTML=" ";
spacerEl.style.display="block";
}
this.pagingDiv.appendChild(pagingEl);
if (i + 1 < (this.childrenCount))
this.pagingDiv.appendChild(spacerEl);
pagingEl = null;
spacerEl = null;
}
if(this.horizontal){
this.pagingDiv.style.width = (this.childrenCount) * 50 + "px";
this.pagingDiv.style.height = "25px";
}
else {
this.pagingDiv.style.height = (this.childrenCount) * 50 + "px";
this.pagingDiv.style.width = "25px";
}
}
this.onMoveIndex(this.carouselIndex);
}
};
return carousel;
})();
function isHorizontalSwipe(xAxis, yAxis) {
var X = xAxis;
var Y = yAxis;
var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2))); //the distance - rounded - in pixels
var r = Math.atan2(Y,X); //angle in radians
var swipeAngle = Math.round(r*180/Math.PI); //angle in degrees
if ( swipeAngle < 0 ) { swipeAngle = 360 - Math.abs(swipeAngle); } // for negative degree values
if (((swipeAngle <= 215) && (swipeAngle >= 155)) || ((swipeAngle <= 45) && (swipeAngle >= 0)) || ((swipeAngle <= 360) && (swipeAngle >= 315))) // horizontal angles with threshold
{return true; }
else {return false}
}
})(af);
Now, on the CSS file when I change .carousel_dots to #carousel_dots as it was originally. The carousel starts working. The problem is I need it as a class not an ID.
I'm pretty sure the problem is in the jquery, somewhere in there I need to set carousel_dots as a class and not an ID, but where?
Any help will be much apreciated, thanks.
jQuery is designed to trigger on HTML selectors, either elements, ID's or Class's. It's very common for it to trigger on ID's because, as you identified, they occur once and that isolates the action to that particular item.
I know that you changed the ID's to Class's because you want to use the CSS class multiple times. You can do this by using Class's. But, to maintain the jQuery logic, you should not change the ID's to Class's for that purpose. Use the ID's to synch with jQuery. Use Class's to control your CSS.
It's difficult to advise you regarding the case you displayed because you didn't identify the initial status and exactly how you changed it. If you can do that, we can be specific about what changes you should make. Good luck.

javascript function didn't work in chrome

i have this function witch shows the user a loadingpanel at postback.
It works fine in IE and Firefox.
But Chrome showed me this Error:
I don't understand why. Does anyone have an idea?
I mean why it works in IE and Firefox. Where is the difference that it doesn't work in Chrome?
(function(){
var emptyFn = function(){};
function lp(d) {
this.converter = d.converter;
this.data = d.path || d.data;
this.imageData = [];
this.multiplier = d.multiplier || 1;
this.padding = d.padding || 0;
this.fps = d.fps || 25;
this.stepsPerFrame = ~~d.stepsPerFrame || 1;
this.trailLength = d.trailLength || 1;
this.pointDistance = d.pointDistance || .05;
this.domClass = d.domClass || 'lp';
this.backgroundColor = d.backgroundColor || 'rgba(0,0,0,0)';
this.fillColor = d.fillColor;
this.strokeColor = d.strokeColor;
this.stepMethod = typeof d.step == 'string' ?
stepMethods[d.step] :
d.step || stepMethods.square;
this._setup = d.setup || emptyFn;
this._teardown = d.teardown || emptyFn;
this._preStep = d.preStep || emptyFn;
this.width = d.width;
this.height = d.height;
this.fullWidth = this.width + 2*this.padding;
this.fullHeight = this.height + 2*this.padding;
this.domClass = d.domClass || 'lp';
this.setup();
}
var argTypes = lp.argTypes = {
DIM: 1,
DEGREE: 2,
RADIUS: 3,
OTHER: 0
};
var argSignatures = lp.argSignatures = {
arc: [1, 1, 3, 2, 2, 0],
bezier: [1, 1, 1, 1, 1, 1, 1, 1],
line: [1,1,1,1]
};
var pathMethods = lp.pathMethods = {
bezier: function(t, p0x, p0y, p1x, p1y, c0x, c0y, c1x, c1y) {
t = 1-t;
var i = 1-t,
x = t*t,
y = i*i,
a = x*t,
b = 3 * x * i,
c = 3 * t * y,
d = y * i;
return [
a * p0x + b * c0x + c * c1x + d * p1x,
a * p0y + b * c0y + c * c1y + d * p1y
]
},
arc: function(t, cx, cy, radius, start, end) {
var point = (end - start) * t + start;
var ret = [
(Math.cos(point) * radius) + cx,
(Math.sin(point) * radius) + cy
];
ret.angle = point;
ret.t = t;
return ret;
},
line: function(t, sx, sy, ex, ey) {
return [
(ex - sx) * t + sx,
(ey - sy) * t + sy
]
}
};
var stepMethods = lp.stepMethods = {
square: function(point, i, f, color, alpha) {
this._.fillRect(point.x - 3, point.y - 3, 6, 6);
},
fader: function(point, i, f, color, alpha) {
this._.beginPath();
if (this._last) {
this._.moveTo(this._last.x, this._last.y);
}
this._.lineTo(point.x, point.y);
this._.closePath();
this._.stroke();
this._last = point;
}
}
lp.prototype = {
setup: function() {
var args,
type,
method,
value,
data = this.data;
this.canvas = document.createElement('canvas');
this._ = this.canvas.getContext('2d');
this.canvas.className = this.domClass;
this.canvas.height = this.fullHeight;
this.canvas.width = this.fullWidth;
this.canvas.innerHTML = "<img src='../img/ContentLoad.gif' width='60px' height='60px' alt='Wird geladen' style='margin-top: 30px;' />"
this.points = [];
for (var i = -1, l = data.length; ++i < l;) {
args = data[i].slice(1);
method = data[i][0];
if (method in argSignatures) for (var a = -1, al = args.length; ++a < al;) {
type = argSignatures[method][a];
value = args[a];
switch (type) {
case argTypes.RADIUS:
value *= this.multiplier;
break;
case argTypes.DIM:
value *= this.multiplier;
value += this.padding;
break;
case argTypes.DEGREE:
value *= Math.PI/180;
break;
};
args[a] = value;
}
args.unshift(0);
for (var r, pd = this.pointDistance, t = pd; t <= 1; t += pd) {
t = Math.round(t*1/pd) / (1/pd);
args[0] = t;
r = pathMethods[method].apply(null, args);
this.points.push({
x: r[0],
y: r[1],
progress: t
});
}
}
this.frame = 0;
if (this.converter && this.converter.setup) {
this.converter.setup(this);
}
},
prep: function(frame) {
if (frame in this.imageData) {
return;
}
this._.clearRect(0, 0, this.fullWidth, this.fullHeight);
this._.fillStyle = this.backgroundColor;
this._.fillRect(0, 0, this.fullWidth, this.fullHeight);
var points = this.points,
pointsLength = points.length,
pd = this.pointDistance,
point,
index,
frameD;
this._setup();
for (var i = -1, l = pointsLength*this.trailLength; ++i < l && !this.stopped;) {
index = frame + i;
point = points[index] || points[index - pointsLength];
if (!point) continue;
this.alpha = Math.round(1000*(i/(l-1)))/1000;
this._.globalAlpha = this.alpha;
if (this.fillColor) {
this._.fillStyle = this.fillColor;
}
if (this.strokeColor) {
this._.strokeStyle = this.strokeColor;
}
frameD = frame/(this.points.length-1);
indexD = i/(l-1);
this._preStep(point, indexD, frameD);
this.stepMethod(point, indexD, frameD);
}
this._teardown();
this.imageData[frame] = (
this._.getImageData(0, 0, this.fullWidth, this.fullWidth)
);
return true;
},
draw: function() {
if (!this.prep(this.frame)) {
this._.clearRect(0, 0, this.fullWidth, this.fullWidth);
this._.putImageData(
this.imageData[this.frame],
0, 0
);
}
if (this.converter && this.converter.step) {
this.converter.step(this);
}
if (!this.iterateFrame()) {
if (this.converter && this.converter.teardown) {
this.converter.teardown(this);
this.converter = null;
}
}
},
iterateFrame: function() {
this.frame += this.stepsPerFrame;
if (this.frame >= this.points.length) {
this.frame = 0;
return false;
}
return true;
},
play: function() {
this.stopped = false;
var hoc = this;
this.timer = setInterval(function(){
hoc.draw();
}, 1000 / this.fps);
},
stop: function() {
this.stopped = true;
this.timer && clearInterval(this.timer);
}
};
window.lp = lp;
}());
function ContentLoader(e) {
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
if (isIE () == 8) {
var div = document.createElement('div');
var img = document.createElement('img');
img.src = '../img/ContentLoad.gif';
div.innerHTML = "<b style='color: #1d4377; z-index: 5000;'>Ihre Anfrage wird bearbeitet...</b><br /><i>...einen Moment bitte...</i><br />";
div.style.cssText = 'position: fixed; z-index: 6000; width: 100%; padding-top: 20%; left: 0; top: 0; height: 100%; text-align: center; background: #fff; filter: alpha(opacity=70);';
div.appendChild(img);
img.style.cssText = 'margin-top:20px;'
document.body.appendChild(div);
} else {
var div = document.createElement('div');
var circle = new lp({
width: 60,
height: 60,
padding: 50,
strokeColor: '#1d4377',
pointDistance: .01,
stepsPerFrame: 4,
trailLength: .8,
step: 'fader',
setup: function () {
this._.lineWidth = 5;
},
path: [
['arc', 25, 25, 25, 0, 360]
]
});
circle.play();
div.innerHTML = "<b style='color: #1d4377; z-index: 5000;'>Ihre Anfrage wird bearbeitet...</b><br /><i>...einen Moment bitte...</i><br />";
div.style.cssText = 'position: fixed; z-index: 6000; width: 100%; padding-top: 20%; left: 0; top: 0; height: 100%; text-align: center; background: #fff; opacity: 0.7;';
div.appendChild(circle.canvas);
document.body.appendChild(div);
}
}
Edit:
I call it like this:
<form id="frmTilgungsaussetzungErgebnis" runat="server" enctype="multipart/form-data" onsubmit="ContentLoader();">
Your function lp is not defined in the else scope.
Try
var circle = new this.lp({
instade
var circle = new lp({

Categories

Resources