How to remove black borders on embed youtube video? - javascript

I need to make the video like this one here:
http://themes.laborator.co/aurum/fashion/home/home-4/?header-type=3&header-top-links=hide&header-cart-icon=5
I'm using jquery plugin. You can see here the code.
The first thing I need to do is to make height something about 550px than borders with some blur effect like in the template.
/*
jQuery backVid plugin
by Rory Standley
http://www.rstandley.co.uk
version: 1.0
licensed under the MIT License
*/
(function ($, window) {
var backVid = function(node, options) {
// Establish our default settings
var settings = $.extend({
ratio: 16/9, // either 4/3 or 16/9
videoId: 'O_OKpl6u5P4',
mute: false,
repeat: true,
width: $(window).width(),
playButtonClass: 'backVid-play',
pauseButtonClass: 'backVid-pause',
muteButtonClass: 'backVid-mute',
unMuteButtonClass: 'backVid-unMute',
volumeUpClass: 'backVid-volume-up',
volumeDownClass: 'backVid-volume-down',
increaseVolumeBy: 10,
mobileBackgrounType: 'colour', // either image/colour
backgroundValue: 'rgb(0,0,0)', // either hex,RGB/Image URL - example (http://www.rstandley.co.uk/laboratory/url_shortner/UxWBHq)
videoFilter: false, // either false/lines/bricks/squares/waves/spots/dashes/crosses
start: 0
}, options);
// First we need to check to see if we have a mobile device or not
if (checkDevice()) {
// Now we need to append our div we will work with to the 'body'
wrapElements();
$('body').append(
$('<div />').attr('id','backVid-video-player')
.css({
'position':'inherit',
'left':0,
'top': -177,
'overflow':'hidden',
'z-index':'1',
'height':'100%',
'width':'100%'
})
);
// Lets build our background value for backVid-stop-clicks
switch(settings.videoFilter){
case 'false':
myFilterBG = '0';
break;
case 'lines':
myFilterBG = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAD0lEQVQImWNgQAX/yeAAAIHCA/0RE2WAAAAAAElFTkSuQmCC)';
break;
case 'bricks':
myFilterBG = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAE0lEQVQImWNgwAT/yRf4j0vFfwAZXgb64t36UQAAAABJRU5ErkJggg==)';
break;
case 'squares':
myFilterBG = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAQElEQVQYlW2OwQ0AMAgCbw7XcMFubj81RVpeGgIcQHK1gJC/+shjtkLNTmpTaZMm05IB76YzfTedaW46k28Opg1VYQ5hW3JdzwAAAABJRU5ErkJggg==)';
break;
case 'waves':
myFilterBG = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAICAYAAADA+m62AAAAJElEQVQYlWNgwAT/sYjhVIRXMbokVsW4TPhPjCJi5clXTBwAAOy+CfekNMf3AAAAAElFTkSuQmCC)';
break;
case 'spots':
myFilterBG = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAEklEQVQImWNgYGD4z0AswK4SAFXuAf8EPy+xAAAAAElFTkSuQmCC)';
break;
case 'dashes':
myFilterBG = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAEklEQVQYlWNgoBL4T7GCoW8FAGEXBfvNSmHvAAAAAElFTkSuQmCC)';
break;
case 'crosses':
myFilterBG = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAMklEQVQYlWNgYGAwZkAFxjjEcApgSOKTIGgSVpOxKcKqmGiFRFuNUwCHGFaT8erCGuAAtV8HLQ/j6goAAAAASUVORK5CYII=)';
break;
default:
myFilterBG = '0'
}
// Now we need to add a layer to stop people clicking on the YouTube video
$('body').append(
$('<div />').attr('id','backVid-stop-clicks')
.css({
'width':'100%',
'height':'100%',
'z-index':'2',
'position':'fixed',
'left':0,
'top':-177,
'background-image': myFilterBG
})
);
} else {
// We have a mobile device, the auto play feature does not work, so we need to use a BG image/colour
if (settings.mobileBackgrounType == 'image') {
// We need to show the image url
if (settings.backgroundValue != '') {
// We can assume we have a value and we must assume that it is a link to an image
$('body').css({
'background': 'url('+settings.backgroundValue+') no-repeat center center fixed',
'-webkit-background-size': 'cover',
'-moz-background-size': 'cover',
'-o-background-size': 'cover',
'background-size': 'cover',
});
}
} else if (settings.mobileBackgrounType == 'colour') {
// We need to show a background colour
if (settings.backgroundValue != '') {
// We can assume we have a value and we must assume that it is a link to an image
$('body').css({
'background': settings.backgroundValue,
'height':'100%',
'width':'100%'
});
}
}
}
// We are using global space in order to talk with the YouTube API
window.player;
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('backVid-video-player', {
width: settings.width,
height: Math.ceil(settings.width / settings.ratio),
videoId: settings.videoId,
playerVars: {
controls: 0,
showinfo: 0,
modestbranding: 1,
wmode: 'transparent'
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
window.onPlayerReady = function(e) {
resize();
if (settings.mute) e.target.mute();
e.target.seekTo(settings.start);
e.target.playVideo();
}
window.onPlayerStateChange = function(state) {
if (state.data === 0 && settings.repeat) {
player.seekTo(settings.start);
}
}
// resize handler updates width, height and offset of player after resize/init
var resize = function() {
var width = $(window).width(),
pWidth,
height = $(window).height(),
pHeight,
$backVidPlayer = $('#backVid-video-player');
// when screen aspect ratio differs from video, video must center and underlay one dimension
if (width / settings.ratio < height) { // if new video height < window height (gap underneath)
pWidth = Math.ceil(height * settings.ratio); // get new player width
$backVidPlayer.width(pWidth).height(height).css({left: (width - pWidth) / 2, top: -117}); // player width is greater, offset left; reset top
} else { // new video width < window width (gap to right)
pHeight = Math.ceil(width / settings.ratio); // get new player height
$backVidPlayer.width(width).height(pHeight).css({left: 0, top: -117}); // player height is greater, offset top; reset left
}
}
$('body').on('click','.' + settings.playButtonClass, function(e) { // play button
e.preventDefault();
player.playVideo();
}).on('click', '.' + settings.pauseButtonClass, function(e) { // pause button
e.preventDefault();
player.pauseVideo();
}).on('click', '.' + settings.muteButtonClass, function(e) { // mute button
e.preventDefault();
(player.isMuted()) ? player.unMute() : player.mute();
}).on('click', '.' + settings.volumeDownClass, function(e) { // volume down button
e.preventDefault();
var currentVolume = player.getVolume();
if (currentVolume < settings.increaseVolumeBy) currentVolume = settings.increaseVolumeBy;
player.setVolume(currentVolume - settings.increaseVolumeBy);
}).on('click', '.' + settings.volumeUpClass, function(e) { // volume up button
e.preventDefault();
if (player.isMuted()) player.unMute(); // if mute is on, unmute
var currentVolume = player.getVolume();
if (currentVolume > 100 - settings.increaseVolumeBy) currentVolume = 100 - settings.increaseVolumeBy;
player.setVolume(currentVolume + settings.increaseVolumeBy);
}).on('click', '.' + settings.unMuteButtonClass, function(e) { // mute button
e.preventDefault();
player.unMute()
});
}
// Load the YouTube API
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Lets create our Plugin
$.fn.backVid = function (options) {
return this.each(function () {
// First lets check to see if we have a mobile device or not
if (!$.data(this, 'backVid_instantiated')) { // let's only run one
$.data(this, 'backVid_instantiated',
backVid(this, options));
}
});
}
function checkDevice() {
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// some code..
return false;
} else {
return true;
}
}
function wrapElements() {
// We are going to wrapp all the elements so we can adjust the z-index
$('body').wrapInner($('<div />').attr('class','backVid-wrapper').css({
'position':'relative',
'z-index':'3'
})
);
}
})(jQuery, window);

Related

How to detect mouse down event on fabric js animated objects

i was playing with Fabric.js and aim is to detect mouse down event on an animated object. Currently images are being animated from bottom to top, and when i press mouse down it just shows coordinate but does not detect clicking on Object.
I also noticed that, when images start their animation, only then i can click/select them, after that they become non-selectable
here is a jsfiddle demo of code. please check and suggest.
my html is :
<h3>Hello Fabric</h3>
<div class="mainCanvasContainer">
<canvas class="mainCanvas" id="mycanvas" width="500px" height="400px"></canvas>
</div>
<div id='info'>
</div>
now here is my Javascript:
$(document).ready(function () {
var canvas_id = 'mycanvas';
function showInfo(text){
$('#info').append('<div> '+text+' </div>');
}
(function () {
var canvas = this.__canvas = new fabric.Canvas(canvas_id, {selection: false});
fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center';
canvas.on('mouse:down', function (options) {
if (options.target) {
showInfo('an object was clicked! ', options.target.type);
}
var cor=options.e.clientX+','+ options.e.clientY;
showInfo(cor);
});
setInterval(function () {
fabric.Image.fromURL('http://www.rashflash.com/fabricjs_animation/img.png', function (img) {
img.scale(0.2);
//img.set('left', fabric.util.getRandomInt(100, 400)).set('top', 450);
//img.movingLeft = !!Math.round(Math.random());
var text = new fabric.Text('hello', {
fontSize: 30,
originX: 'center',
originY: 'center'
});
var group = new fabric.Group([img, text]);
group.set('left', fabric.util.getRandomInt(100, 400)).set('top', 420);
canvas.add(group);
});
}, 1000);
(function animate() {
canvas.forEachObject(function (obj) {
if (!obj) {
return;
}
// obj.left += (obj.movingLeft ? -1 : 1);
obj.top -= 1;
if (obj.left > 500 || obj.top < 0) {
canvas.remove(obj);
}
});
canvas.renderAll();
fabric.util.requestAnimFrame(animate);
})();
})();
});
RashFlash, you are missing setCoords() function when you animate.
Updated function animate:
(function animate() {
canvas.forEachObject(function (obj) {
if (!obj) {
return;
}
// obj.left += (obj.movingLeft ? -1 : 1);
obj.top -= 1;
if (obj.left > 500 || obj.top < 0) {
canvas.remove(obj);
}
obj.setCoords();
});
canvas.renderAll();
fabric.util.requestAnimFrame(animate);
})();
})();
Also, updated fiddle

Previous and next image link in JavaScript

I need help for the slider on TweenMax.js
The problem:
This example has 4 images, on click each images will open in a fullscreen.
But i am not getting the previous screen link and next screen link in fullscreen.
Expected Result: once image is clicked, it should get previous image hyperlink and next hyperlink in all the sliders
Please Note : Now it is working for last image and first image.
even though i click any image
Please accept my apologies, CODE is very big !
JSFIDDLE :
http://jsfiddle.net/goo08gg5/11/
Any help is appreciated, thanks in advance.
UPDATE:
I feel this place in JS, we need to make the changes, but i might be wrong
//next image link
TweenLite.set($expander_nav.last(), {
x : 160,
right : 4,
left : 'auto',
delay : delay
});
//first image link
TweenLite.set($expander_nav.first(), {
x : -160,
left : 4,
right : 'auto',
delay : delay,
onComplete : function () {
// add content to title overlay after delay
$title.html(self.$cur_circle.siblings('.tagline').html());
}
});
JAVASCRIPT
var HeroCircles = function(el) {
this.$el = $(el);
this.$circles = this.$el.find('.circle');
this.$expander = this.$el.find('.circle-expander');
this.$cur_circle = null;
};
HeroCircles.prototype._placeBG = function() {
// get parent position and dimensions
var self = this,
parent_pos = this.$el.offset(),
parent_width = this.$el.width(),
parent_height = this.$el.height();
this.$circles.each(function() {
var $circle = $(this),
offset = $circle.offset(),
$bg = $circle.children('.bg');
// set position
$bg.css({
'top': parent_pos.top - offset.top + 'px',
'left': parent_pos.left - offset.left + 'px',
'width': parent_width + 'px',
'height': parent_height + 'px'
});
});
};
HeroCircles.prototype._animateInTitle = function(delay) {
var self = this,
$title = this.$expander.children('.title-overlay'),
cur_class = this.$cur_circle.data('name'),
$expander_nav = this.$expander.children('.expander-nav').children('a').not('.' + cur_class);
TweenLite.set($expander_nav.last(), { x: 160, right: 4, left: 'auto', delay: delay });
//Last image
TweenLite.set($expander_nav.first(), {
x: -160,
left: 4,
right: 'auto',
delay: delay,
onComplete: function() {
// add content to title overlay after delay
$title.html(self.$cur_circle.siblings('.tagline').html());
}
});
//Firstimage
// animate in title overlay
TweenLite.to($title, 0.5, {
y: 40,
delay: delay,
ease: Back.easeOut
});
TweenLite.to($expander_nav, 0.15, {
x: 0,
delay: delay + 0.5
});
};
HeroCircles.prototype._animateOutTitle = function() {
var $title = this.$expander.children('.title-overlay'),
cur_class = this.$cur_circle.data('name'),
$expander_nav = this.$expander.children('.expander-nav').children('a').not('.' + cur_class);
// animate out title overlay
TweenLite.to($title, 0.5, {
y: $title.outerHeight()
});
// animate out circles
TweenLite.to($expander_nav.first(), 0.15, {
x: -160
});
TweenLite.to($expander_nav.last(), 0.15, {
x: 160
});
};
HeroCircles.prototype._animateIn = function(circle) {
var $circle = $(circle),
$border = $circle.siblings('.border'),
img = $circle.children('.bg').data('bg');
// set current circle
this.$cur_circle = $circle;
// set bg image for expander div
this.$expander.css('z-index', 4);
this.$expander.children('.bg').css('background-image', 'url(' + img + ')');
// add active class to li
$circle.parent('li').addClass('active');
// expand circle
TweenLite.to($border, 0.3, {
scale: 7
});
// fade in expander
TweenLite.to(this.$expander, 0.5, {
opacity: 1,
delay: 0.5,
onComplete: function() {
TweenLite.set($border, { scale: 1 });
}
});
// animate in title overlay
this._animateInTitle(1);
};
HeroCircles.prototype._animateOut = function() {
var self = this;
// remove active class and scale down border
this.$el.find('li').removeClass('active');
// animate out title
this._animateOutTitle();
// fade out expander
TweenLite.to(this.$expander, 0.5, {
opacity: 0,
delay: 0.5,
onComplete: function() {
self.$expander.css({
'z-index': -1
});
}
});
};
HeroCircles.prototype._animateSwitch = function(circle) {
this._animateOutTitle();
this.$cur_circle = $(circle);
var img = this.$cur_circle.children('.bg').data('bg'),
$bg = this.$expander.children('.bg');
// switch active class
this.$el.find('li').removeClass('active');
this.$cur_circle.parent('li').addClass('active');
TweenLite.to($bg, 0.3, {
opacity: 0,
delay: 0.5,
onComplete: function() {
$bg.css('background-image', 'url(' + img + ')');
TweenLite.to($bg, 0.3, { opacity: 1 });
}
});
this._animateInTitle(1);
};
HeroCircles.prototype.init = function() {
var self = this;
this._placeBG();
// add click events
this.$el.on('click', '.circle', function() {
self._animateIn(this);
});
this.$el.find('.close-btn').on('click', function(e) {
e.preventDefault();
self._animateOut();
});
this.$expander.children('.expander-nav').on('click', 'a', function(e) {
e.preventDefault();
var new_class = $(this).attr('class'),
$circle = self.$el.find('ul .' + new_class);
console.log("new class is", new_class, "new circle is", $circle[0]);
self._animateSwitch($circle);
});
};
HeroCircles.prototype.initMobile = function() {
var self = this,
$mobile_slider = this.$el.find('.mobile-slider');
this.$el.on('click', '.circle', function() {
var $this = $(this),
bg = $this.children('.bg').data('bg');
self.$circles.removeClass('active');
$this.addClass('active');
$mobile_slider.html('<div>' + $this.siblings('.tagline').html() + '</div>');
$mobile_slider.css('background-image', 'url(' + bg + ')');
});
this.$circles.first().trigger('click');
};
var hero_circles = new HeroCircles('.hero-circles');
if ( window.innerWidth > 580 ) {
hero_circles.init();
} else {
hero_circles.initMobile();
}
I have make
Expected Result: once image is clicked, it should get previous image
hyperlink and next hyperlink in all the sliders
But i dont know how work this fadeIn and fadeOut circle.
This script work fine for next and prev slide, but the animation slide is no good. but it's work !
I have add a index of clicked circle for next and prev slide.
please see: http://jsfiddle.net/gw4eqg92/

Fabric.js Sticky Note type text wrap

I am trying to make a sticky note type utility with the fabric canvas. It will help to be used as annotators.
I want the text to wrap by itself at the given rectangle's width.
Can someone update my fiddle work??
Suggestions are appreciated. Regards...
The following is the link to a part of my fiddle:
http://jsfiddle.net/U7E9q/5/
var canvas = new fabric.Canvas('fabric-canvas');
canvas.hoverCursor = 'pointer';
var text = new fabric.IText("Enter Text Here ",{
fontSize: 20,
top: 100,
left: 100,
backgroundColor: '#faa',
lockScalingX: true,
lockScalingY: true,
selectable: true
});
//alert(text.text);
var rect = new fabric.Rect({
text_field: text,
width: 200,
height: 50,
fill: '#faa',
rx: 10,
ry: 10,
top: 100,
left: 100
});
canvas.add(rect);
canvas.add(text);
canvas.on('object:moving', function (event){
canvas.renderAll();
});
createListenersKeyboard();
function createListenersKeyboard() {
document.onkeydown = onKeyDownHandler;
//document.onkeyup = onKeyUpHandler;
}
function onKeyDownHandler(event) {
//event.preventDefault();
var key;
if(window.event){
key = window.event.keyCode;
}
else{
key = event.keyCode;
}
switch(key){
//////////////
// Shortcuts
//////////////
// Copy (Ctrl+C)
case 67: // Ctrl+C
if(ableToShortcut()){
if(event.ctrlKey){
event.preventDefault();
copy();
}
}
break;
// Delete (Ctrl+D)
case 127: // Ctrl+D
if(ableToShortcut()){
if(event.deleteKey){
delet();
}
}
break;
// Paste (Ctrl+V)
case 86: // Ctrl+V
if(ableToShortcut()){
if(event.ctrlKey){
event.preventDefault();
paste();
}
}
break;
default:
// TODO
break;
}
}
function ableToShortcut(){
/*
TODO check all cases for this
if($("textarea").is(":focus")){
return false;
}
if($(":text").is(":focus")){
return false;
}
*/
return true;
}
function copy(){
if(canvas.getActiveGroup()){
for(var i in canvas.getActiveGroup().objects){
var object = fabric.util.object.clone(canvas.getActiveGroup().objects[i]);
object.set("top", object.top+5);
object.set("left", object.left+5);
copiedObjects[i] = object;
}
}
else if(canvas.getActiveObject()){
var object = fabric.util.object.clone(canvas.getActiveObject());
object.set("top", object.top+5);
object.set("left", object.left+5);
copiedObject = object;
copiedObjects = new Array();
}
}
function paste(){
if(copiedObjects.length > 0){
for(var i in copiedObjects){
canvas.add(copiedObjects[i]);
}
}
else if(copiedObject){
canvas.add(copiedObject);
}
canvas.renderAll();
}
function delet(){
var activeObject = canvas.getActiveObject();
canvas.remove(activeObject);
console.log('after remove getActiveObject(): ', canvas.getActiveObject(), activeObject === canvas.getActiveObject());
canvas.renderAll();
}
If you manage the sticky note as a grouped rect and text you can improve the same behavior. When you need to edit the text inside the group, you just ungroup and clone the elements, append the cloned elements to the canvas and set text as editable.
You need to handle an event like double click to handle this behavior and then handle the mousedown or other interactivity with canvas to regroup them.
http://jsfiddle.net/4HE3U/1/
Above is one fiddle that can satisfy you
Basically i have made one group of Text and Rectangle and i have added it to canvas. There is only one change you need to make is that you can take one textbox to get current sticky note text content as we can not edit text of i-text online once we are adding it any group. Currently there is no way for IText to handle the events as they are not handed down to it if it's contained in a group. I think this is also the prefered way to handle that as it would confuse the user - what if he starts to edit multiple texts. This might end up in a mess. Maybe you can rework your script a little to workaround this problems.
I have added Text and Rectangle
var canvas = new fabric.Canvas('fabric-canvas');
canvas.hoverCursor = 'pointer';
var text = new fabric.IText("Enter Text Here ",{
fontSize: 20,
top: 100,
left: 100,
backgroundColor: '#faa',
lockScalingX: true,
lockScalingY: true,
selectable: true
});
//alert(text.text);
var rect = new fabric.Rect({
text_field: text,
width: 200,
height: 50,
fill: '#faa',
rx: 10,
ry: 10,
top: 100,
left: 100
});
var group = new fabric.Group([ rect, text ], {
left: 100,
top: 100,
lockScalingX: true,
lockScalingY: true,
hasRotatingPoint: false,
transparentCorners: false,
cornerSize: 7
});
canvas.add(group);
//canvas.add(text);
canvas.on('object:moving', function (event){
canvas.renderAll();
});
createListenersKeyboard();
function createListenersKeyboard() {
document.onkeydown = onKeyDownHandler;
//document.onkeyup = onKeyUpHandler;
}
function onKeyDownHandler(event) {
//event.preventDefault();
var key;
if(window.event){
key = window.event.keyCode;
}
else{
key = event.keyCode;
}
switch(key){
//////////////
// Shortcuts
//////////////
// Copy (Ctrl+C)
case 67: // Ctrl+C
if(ableToShortcut()){
if(event.ctrlKey){
event.preventDefault();
copy();
}
}
break;
// Delete (Ctrl+D)
case 127: // Ctrl+D
if(ableToShortcut()){
if(event.deleteKey){
delet();
}
}
break;
// Paste (Ctrl+V)
case 86: // Ctrl+V
if(ableToShortcut()){
if(event.ctrlKey){
event.preventDefault();
paste();
}
}
break;
default:
// TODO
break;
}
}
function ableToShortcut(){
/*
TODO check all cases for this
if($("textarea").is(":focus")){
return false;
}
if($(":text").is(":focus")){
return false;
}
*/
return true;
}
function copy(){
if(canvas.getActiveGroup()){
for(var i in canvas.getActiveGroup().objects){
var object = fabric.util.object.clone(canvas.getActiveGroup().objects[i]);
object.set("top", object.top+5);
object.set("left", object.left+5);
copiedObjects[i] = object;
}
}
else if(canvas.getActiveObject()){
var object = fabric.util.object.clone(canvas.getActiveObject());
object.set("top", object.top+5);
object.set("left", object.left+5);
copiedObject = object;
copiedObjects = new Array();
}
}
function paste(){
if(copiedObjects.length > 0){
for(var i in copiedObjects){
canvas.add(copiedObjects[i]);
}
}
else if(copiedObject){
canvas.add(copiedObject);
}
canvas.renderAll();
}
function delet(){
var activeObject = canvas.getActiveObject();
canvas.remove(activeObject);
console.log('after remove getActiveObject(): ', canvas.getActiveObject(), activeObject === canvas.getActiveObject());
canvas.renderAll();
}
<canvas id="fabric-canvas" width="400" height="400"></canvas>
Here is Sticky note functionality. Text wrap working and font size changes w.r.t sticky note width and height. Editing mode activates on double click.
export const createStickyNotes = (canvas, options) => {
fabric.StickyNote = fabric.util.createClass(fabric.Group, {
type: "StickyNote",
initialize: function (options) {
this.set(options);
var height = this.height;
var width = this.width;
this.rectObj = new fabric.Rect({
width: width,
height: height,
fill: this.rectObj?.fill ?? "rgba(251,201,112,1)",
originX: "center",
originY: "center",
objectCaching: false,
stateProperties: ["fill"],
});
this.textObj = new fabric.Textbox(this.textObj?.text ?? "Notes", {
originX: "center",
originY: "center",
textAlign: "center",
width: 100,
hasControls: false,
fontSize: this.textObj?.fontSize ?? 30,
lineHeight: 1,
stateProperties: ["text", "fontSize"],
scaleX: this.textObj?.scaleX ?? 1,
scaleY: this.textObj?.scaleY ?? 1,
objectCaching: false,
breakWords: true,
fontFamily: "Open Sans",
});
this._objects = [this.rectObj, this.textObj];
// this custom _set function will set custom properties value to object when it will load from json.
// at that time loadFromJson function will call this initialize function.
// this._setCustomProperties(this.options);
canvas.renderAll();
//evenet will fire if the object is double clicked by mouse
this.on("mousedblclick", (e) => {
var pasteFlag = false;
var scaling = e.target.getScaledWidth() / 100;
var textForEditing;
canvas.bringToFront(e.target);
e.target.selectable = false;
const [rectObj, textObj] = this.getObjects();
textObj.clone(function (clonedObj) {
clonedObj.set({
left: e.target.left,
top: e.target.top,
lockMovementY: true,
lockMovementX: true,
hasBorders: false,
scaleX: scaling,
scaleY: scaling,
breakWords: true,
width: textObj.width,
stateProperties: [],
});
textForEditing = clonedObj;
});
this.remove(textObj);
canvas.add(textForEditing);
canvas.setActiveObject(textForEditing);
textForEditing.enterEditing();
textForEditing.selectAll();
textForEditing.paste = (function (paste) {
return function (e) {
disableScrolling();
pasteFlag = true;
};
})(textForEditing.paste);
textForEditing.on("changed", function (e) {
var fontSize = textForEditing.fontSize;
var charCount = Math.max(textForEditing._text.length, 1);
var charWR =
(textForEditing.textLines.length * width) / (charCount * fontSize);
if (textForEditing.height < height - 15) {
fontSize = Math.min(
Math.sqrt(
((height - 10 - fontSize) / 1.16) *
(width / (charCount * charWR))
),
30
);
}
if (textForEditing.height > height - 15) {
fontSize = Math.sqrt(
((height - 10) / 1.16) * (width / (charCount * charWR))
);
}
if (pasteFlag) {
pasteFlag = false;
while (
textForEditing.height > height - 15 &&
textForEditing.fontSize > 0
) {
fontSize = textForEditing.fontSize -= 0.2;
canvas.renderAll();
}
}
textForEditing.fontSize = fontSize;
});
textForEditing.on("editing:exited", () => {
enableScrolling();
canvas.setActiveObject(textObj);
textObj.set({
text: textForEditing.text,
fontSize: textForEditing.fontSize,
visible: true,
});
this.add(textObj);
this.selectable = true;
canvas.remove(textForEditing);
canvas.discardActiveObject();
});
});
function disableScrolling() {
var x = window.scrollX;
var y = window.scrollY;
window.onscroll = function () {
window.scrollTo(x, y);
};
}
var _wrapLine = function (_line, lineIndex, desiredWidth, reservedSpace) {
var lineWidth = 0,
splitByGrapheme = this.splitByGrapheme,
graphemeLines = [],
line = [],
// spaces in different languges?
words = splitByGrapheme
? fabric.util.string.graphemeSplit(_line)
: _line.split(this._wordJoiners),
word = "",
offset = 0,
infix = splitByGrapheme ? "" : " ",
wordWidth = 0,
infixWidth = 0,
largestWordWidth = 0,
lineJustStarted = true,
additionalSpace = splitByGrapheme ? 0 : this._getWidthOfCharSpacing();
reservedSpace = reservedSpace || 0;
desiredWidth -= reservedSpace;
for (var i = 0; i < words.length; i++) {
// i would avoid resplitting the graphemes
word = fabric.util.string.graphemeSplit(words[i]);
wordWidth = this._measureWord(word, lineIndex, offset);
offset += word.length;
// Break the line if a word is wider than the set width
if (this.breakWords && wordWidth >= desiredWidth) {
if (!lineJustStarted) {
graphemeLines.push(line);
line = [];
lineWidth = 0;
lineJustStarted = true;
}
this.fontSize *= desiredWidth / (wordWidth + 1);
// Loop through each character in word
for (var w = 0; w < word.length; w++) {
var letter = word[w];
var letterWidth =
(this.getMeasuringContext().measureText(letter).width *
this.fontSize) /
this.CACHE_FONT_SIZE;
line.push(letter);
lineWidth += letterWidth;
}
word = [];
} else {
lineWidth += infixWidth + wordWidth - additionalSpace;
}
if (lineWidth >= desiredWidth && !lineJustStarted) {
graphemeLines.push(line);
line = [];
lineWidth = wordWidth;
lineJustStarted = true;
} else {
lineWidth += additionalSpace;
}
if (!lineJustStarted) {
line.push(infix);
}
line = line.concat(word);
infixWidth = this._measureWord([infix], lineIndex, offset);
offset++;
lineJustStarted = false;
// keep track of largest word
if (wordWidth > largestWordWidth && !this.breakWords) {
largestWordWidth = wordWidth;
}
}
i && graphemeLines.push(line);
if (largestWordWidth + reservedSpace > this.dynamicMinWidth) {
this.dynamicMinWidth =
largestWordWidth - additionalSpace + reservedSpace;
}
return graphemeLines;
};
fabric.util.object.extend(fabric.Textbox.prototype, {
_wrapLine: _wrapLine,
});
function enableScrolling() {
window.onscroll = function () {};
}
},
toObject: function (propertiesToInclude) {
// This function is used for serialize this object. (used for create json)
// not inlclude this.textObj and this.rectObj into json because when object will load from json, init fucntion of this class is called and it will assign this two object textObj and rectObj again.
var obj = this.callSuper(
"toObject",
[
"objectCaching",
"textObj",
"rectObj",
// ... property list that you want to add into json when this object is convert into json using toJSON() function. (serialize)
].concat(propertiesToInclude)
);
// delete objects array from json because then object load from json, Init function will call. which will automatically re-assign object and assign _object array.
delete obj.objects;
return obj;
},
});
fabric.StickyNote.async = true;
fabric.StickyNote.fromObject = function (object, callback) {
// This function is used for deserialize json and convert object json into button object again. (called when we call loadFromJson() fucntion on canvas)
return fabric.Object._fromObject("StickyNote", object, callback);
};
return new fabric.StickyNote(options);
};
//How to use
var options = {
width: 100,
height: 100,
originX: "center",
originY: "center",
};
var notes = StickyNotes(canvas, options);
canvas.add(notes);

Cloudzoom and woocommerce attributes

I cannot get cloudzoom to work with my woocommerce site, every time I choose an attribute ie size the main image disappears, it is like cloudzoom is trying to force an attribute image. I am absolutely pants at javascript and looking through the file I cannot see where I need to edit or delete the code. Any help would be greatly appreciated, I don't need the atribute image function to work at all so just stripping out the code would suit me. Here is the code...
(function ($) {
$(document).ready(function () {
$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
});
function format(str) {
for (var i = 1; i < arguments.length; i++) {
str = str.replace('%' + (i - 1), arguments[i]);
}
return str;
}
function CloudZoom(jWin, opts) {
var sImg = $('img', jWin);
var img1;
var img2;
var zoomDiv = null;
var $mouseTrap = null;
var lens = null;
var $tint = null;
var softFocus = null;
var $ie6Fix = null;
var zoomImage;
var controlTimer = 0;
var cw, ch;
var destU = 0;
var destV = 0;
var currV = 0;
var currU = 0;
var filesLoaded = 0;
var mx,
my;
var ctx = this, zw;
// Display an image loading message. This message gets deleted when the images have loaded and the zoom init function is called.
// We add a small delay before the message is displayed to avoid the message flicking on then off again virtually immediately if the
// images load really fast, e.g. from the cache.
//var ctx = this;
setTimeout(function () {
// <img src="/images/loading.gif"/>
if ($mouseTrap === null) {
var w = jWin.width();
jWin.parent().append(format('<div style="width:%0px;position:absolute;top:75%;left:%1px;text-align:center" class="cloud-zoom-loading" >Loading...</div>', w / 3, (w / 2) - (w / 6))).find(':last').css('opacity', 0.5);
}
}, 200);
var ie6FixRemove = function () {
if ($ie6Fix !== null) {
$ie6Fix.remove();
$ie6Fix = null;
}
};
// Removes cursor, tint layer, blur layer etc.
this.removeBits = function () {
//$mouseTrap.unbind();
if (lens) {
lens.remove();
lens = null;
}
if ($tint) {
$tint.remove();
$tint = null;
}
if (softFocus) {
softFocus.remove();
softFocus = null;
}
ie6FixRemove();
$('.cloud-zoom-loading', jWin.parent()).remove();
};
this.destroy = function () {
jWin.data('zoom', null);
if ($mouseTrap) {
$mouseTrap.unbind();
$mouseTrap.remove();
$mouseTrap = null;
}
if (zoomDiv) {
zoomDiv.remove();
zoomDiv = null;
}
//ie6FixRemove();
this.removeBits();
// DON'T FORGET TO REMOVE JQUERY 'DATA' VALUES
};
// This is called when the zoom window has faded out so it can be removed.
this.fadedOut = function () {
if (zoomDiv) {
zoomDiv.remove();
zoomDiv = null;
}
this.removeBits();
//ie6FixRemove();
};
this.controlLoop = function () {
if (lens) {
var x = (mx - sImg.offset().left - (cw * 0.5)) >> 0;
var y = (my - sImg.offset().top - (ch * 0.5)) >> 0;
if (x < 0) {
x = 0;
}
else if (x > (sImg.outerWidth() - cw)) {
x = (sImg.outerWidth() - cw);
}
if (y < 0) {
y = 0;
}
else if (y > (sImg.outerHeight() - ch)) {
y = (sImg.outerHeight() - ch);
}
lens.css({
left: x,
top: y
});
lens.css('background-position', (-x) + 'px ' + (-y) + 'px');
destU = (((x) / sImg.outerWidth()) * zoomImage.width) >> 0;
destV = (((y) / sImg.outerHeight()) * zoomImage.height) >> 0;
currU += (destU - currU) / opts.smoothMove;
currV += (destV - currV) / opts.smoothMove;
zoomDiv.css('background-position', (-(currU >> 0) + 'px ') + (-(currV >> 0) + 'px'));
}
controlTimer = setTimeout(function () {
ctx.controlLoop();
}, 30);
};
this.init2 = function (img, id) {
filesLoaded++;
//console.log(img.src + ' ' + id + ' ' + img.width);
if (id === 1) {
zoomImage = img;
}
//this.images[id] = img;
if (filesLoaded === 2) {
this.init();
}
};
/* Init function start. */
this.init = function () {
// Remove loading message (if present);
$('.cloud-zoom-loading', jWin.parent()).remove();
/* Add a box (mouseTrap) over the small image to trap mouse events.
It has priority over zoom window to avoid issues with inner zoom.
We need the dummy background image as IE does not trap mouse events on
transparent parts of a div.
*/
$mouseTrap = jWin.parent().append(format("<div class='mousetrap' style='background-image:url(\".\");z-index:3;position:absolute;width:%0px;height:%1px;left:%2px;top:%3px;\'></div>", sImg.outerWidth(), sImg.outerHeight(), 0, 0)).find(':last');
//////////////////////////////////////////////////////////////////////
/* Do as little as possible in mousemove event to prevent slowdown. */
$mouseTrap.bind('mousemove', this, function (event) {
// Just update the mouse position
mx = event.pageX;
my = event.pageY;
});
//////////////////////////////////////////////////////////////////////
$mouseTrap.bind('mouseleave', this, function (event) {
clearTimeout(controlTimer);
//event.data.removeBits();
if(lens) { lens.fadeOut(299); }
if($tint) { $tint.fadeOut(299); }
if(softFocus) { softFocus.fadeOut(299); }
zoomDiv.fadeOut(300, function () {
ctx.fadedOut();
});
return false;
});
//////////////////////////////////////////////////////////////////////
$mouseTrap.bind('mouseenter', this, function (event) {
mx = event.pageX;
my = event.pageY;
zw = event.data;
if (zoomDiv) {
zoomDiv.stop(true, false);
zoomDiv.remove();
}
var xPos = opts.adjustX,
yPos = opts.adjustY;
var siw = sImg.outerWidth();
var sih = sImg.outerHeight();
var w = opts.zoomWidth;
var h = opts.zoomHeight;
if (opts.zoomWidth == 'auto') {
w = siw;
}
if (opts.zoomHeight == 'auto') {
h = sih;
}
//$('#info').text( xPos + ' ' + yPos + ' ' + siw + ' ' + sih );
var appendTo = jWin.parent(); // attach to the wrapper
switch (opts.position) {
case 'top':
yPos -= h; // + opts.adjustY;
break;
case 'right':
xPos += siw; // + opts.adjustX;
break;
case 'bottom':
yPos += sih; // + opts.adjustY;
break;
case 'left':
xPos -= w; // + opts.adjustX;
break;
case 'inside':
w = siw;
h = sih;
break;
// All other values, try and find an id in the dom to attach to.
default:
appendTo = $('#' + opts.position);
// If dom element doesn't exit, just use 'right' position as default.
if (!appendTo.length) {
appendTo = jWin;
xPos += siw; //+ opts.adjustX;
yPos += sih; // + opts.adjustY;
} else {
w = appendTo.innerWidth();
h = appendTo.innerHeight();
}
}
zoomDiv = appendTo.append(format('<div id="cloud-zoom-big" class="cloud-zoom-big" style="display:none;position:absolute;left:%0px;top:%1px;width:%2px;height:%3px;background-image:url(\'%4\');z-index:2;"></div>', xPos, yPos, w, h, zoomImage.src)).find(':last');
// Add the title from title tag.
if (sImg.attr('title') && opts.showTitle) {
zoomDiv.append(format('<div class="cloud-zoom-title">%0</div>', sImg.attr('title'))).find(':last').css('opacity', opts.titleOpacity);
}
// Fix ie6 select elements wrong z-index bug. Placing an iFrame over the select element solves the issue...
if ($.browser.msie && $.browser.version < 7) {
$ie6Fix = $('<iframe frameborder="0" src="#"></iframe>').css({
position: "absolute",
left: xPos,
top: yPos,
zIndex: 99,
width: w,
height: h
}).insertBefore(zoomDiv);
}
zoomDiv.fadeIn(500);
if (lens) {
lens.remove();
lens = null;
} /* Work out size of cursor */
cw = (sImg.outerWidth() / zoomImage.width) * zoomDiv.width();
ch = (sImg.outerHeight() / zoomImage.height) * zoomDiv.height();
// Attach mouse, initially invisible to prevent first frame glitch
lens = jWin.append(format("<div class = 'cloud-zoom-lens' style='display:none;z-index:1;position:absolute;width:%0px;height:%1px;opacity:0.4'></div>", cw, ch)).find(':last');
$mouseTrap.css('cursor', lens.css('cursor'));
var noTrans = false;
// Init tint layer if needed. (Not relevant if using inside mode)
if (opts.tint) {
/* lens.css('background', 'url("' + sImg.attr('src') + '")'); */
$tint = jWin.append(format('<div style="display:none;position:absolute; left:0px; top:0px; width:%0px; height:%1px; background-color:%2;" />', sImg.outerWidth(), sImg.outerHeight(), opts.tint)).find(':last');
$tint.css('opacity', opts.tintOpacity);
noTrans = true;
$tint.fadeIn(500);
}
if (opts.softFocus) {
lens.css('background', 'url("' + sImg.attr('src') + '")');
softFocus = jWin.append(format('<div style="position:absolute;display:none;top:2px; left:2px; width:%0px; height:%1px;" />', sImg.outerWidth() - 2, sImg.outerHeight() - 2, opts.tint)).find(':last');
softFocus.css('background', 'url("' + sImg.attr('src') + '")');
softFocus.css('opacity', 0.5);
noTrans = true;
softFocus.fadeIn(500);
}
if (!noTrans) {
lens.css('opacity', opts.lensOpacity);
}
if ( opts.position !== 'inside' ) { lens.fadeIn(500); }
// Start processing.
zw.controlLoop();
return; // Don't return false here otherwise opera will not detect change of the mouse pointer type.
});
};
img1 = new Image();
$(img1).load(function () {
ctx.init2(this, 0);
});
img1.src = sImg.attr('src');
img2 = new Image();
$(img2).load(function () {
ctx.init2(this, 1);
});
img2.src = jWin.attr('href');
}
$.fn.CloudZoom = function (options) {
// IE6 background image flicker fix
try {
document.execCommand("BackgroundImageCache", false, true);
} catch (e) {}
this.each(function () {
var relOpts, opts;
// Hmm...eval...slap on wrist.
eval('var a = {' + $(this).attr('rel') + '}');
relOpts = a;
if ($(this).is('.cloud-zoom')) {
$(this).css({
'position': 'relative',
'display': 'block'
});
$('img', $(this)).css({
'display': 'block'
});
// Wrap an outer div around the link so we can attach things without them becoming part of the link.
// But not if wrap already exists.
if ($(this).parent().attr('id') != 'wrap') {
$(this).wrap('<div id="wrap" style="top:0px;z-index:4;position:relative;"></div>');
}
opts = $.extend({}, $.fn.CloudZoom.defaults, options);
opts = $.extend({}, opts, relOpts);
$(this).data('zoom', new CloudZoom($(this), opts));
} else if ($(this).is('.cloud-zoom-gallery')) {
opts = $.extend({}, relOpts, options);
$(this).data('relOpts', opts);
$(this).bind('click', $(this), function (event) {
var data = event.data.data('relOpts');
// Destroy the previous zoom
$('#' + data.useZoom).data('zoom').destroy();
// Change the biglink to point to the new big image.
$('#' + data.useZoom).attr('href', event.data.attr('href'));
// Change the small image to point to the new small image.
$('#' + data.useZoom + ' img').attr('src', event.data.data('relOpts').smallImage);
// Init a new zoom with the new images.
$('#zoom-cb').attr('href', event.data.attr('href'));
$('#' + event.data.data('relOpts').useZoom).CloudZoom();
return false;
});
}
});
return this;
};
$.fn.CloudZoom.defaults = {
zoomWidth: 'auto',
zoomHeight: 'auto',
position: 'right',
tint: false,
tintOpacity: 0.5,
lensOpacity: 0.5,
softFocus: false,
smoothMove: 3,
showTitle: false,
titleOpacity: 0.5,
adjustX: 0,
adjustY: 0
};
})(jQuery);

global javascript function is not being called onchange event of a file selection

I have a javascript function which I am calling from the onChange event of the file selection box.
function cropper(){}
When I am trying to call this function from the onchange event of the file selection it is not working. I am calling it like
<label>Upload Photo:</label>
<input type="file" id="image_file" name="picture1" onchange="cropper()"/><br>
if I change the definition of function to like below it works.
$(document).ready(function(){
$(#image_file).change(function(){
});
});
Could anyone please help me how to achieve it using the first approach. Thanks in advance.
JSFiddle Link:
http://jsfiddle.net/ashishtyagi10/M5sqK/
There are few problems here
There is a syntax error cropper is not properly closed. There is a missing } at the end of the function
jQuery UI is not enabled
Your code is within load handler which means the cropper is not a global method. You need to select no-wrap body
Try
var selectImgWidth, selectImgHeight, jcrop_api, boundx, boundy, isError = false;
function cropper() {
var previewId = document.getElementById('load_img');
var thumbId = document.getElementById('thumb');
previewId.src = '';
$('#image_div').hide();
var flag = 0;
// Get selected file parameters
var selectedImg = $('#image_file')[0].files[0];
//Check the select file is JPG,PNG or GIF image
var regex = /^(image\/jpeg|image\/png)$/i;
if (!regex.test(selectedImg.type)) {
$('.error').html('Please select a valid image file (jpg and png are allowed)').fadeIn(500);
flag++;
isError = true;
}
if (flag === 0) {
isError = false;
$('.error').hide(); //if file is correct then hide the error message
// Preview the selected image with object of HTML5 FileReader class
// Make the HTML5 FileReader Object
var oReader = new FileReader();
oReader.onload = function (e) {
// e.target.result is the DataURL (temporary source of the image)
thumbId.src = previewId.src = e.target.result;
// FileReader onload event handler
previewId.onload = function () {
$("#dialog").dialog("open"); //--> this is where dialog box is opened
// display the image with fading effect
$('#image_div').fadeIn(500);
selectImgWidth = previewId.naturalWidth; //set the global image width
selectImgHeight = previewId.naturalHeight; //set the global image height
// Create variables (in this scope) to hold the Jcrop API and image size
// destroy Jcrop if it is already existed
if (typeof jcrop_api !== 'undefined') jcrop_api.destroy();
// initialize Jcrop Plugin on the selected image
$('#load_img').Jcrop({
minSize: [32, 32], // min crop size
// aspectRatio : 1, // keep aspect ratio 1:1
bgFade: true, // use fade effect
bgOpacity: .3, // fade opacity
onChange: showThumbnail,
onSelect: showThumbnail
}, function () {
// use the Jcrop API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the Jcrop API in the jcrop_api variable
jcrop_api = this;
});
};
};
// read selected file as DataURL
oReader.readAsDataURL(selectedImg);
}
}
function showThumbnail(e) {
var rx = 155 / e.w; //155 is the width of outer div of your profile pic
var ry = 190 / e.h; //190 is the height of outer div of your profile pic
$('#w').val(e.w);
$('#h').val(e.h);
$('#w1').val(e.w);
$('#h1').val(e.h);
$('#x1').val(e.x);
$('#y1').val(e.y);
$('#x2').val(e.x2);
$('#y2').val(e.y2);
$('#thumb').css({
width: Math.round(rx * selectImgWidth) + 'px',
height: Math.round(ry * selectImgHeight) + 'px',
marginLeft: '-' + Math.round(rx * e.x) + 'px',
marginTop: '-' + Math.round(ry * e.y) + 'px'
});
}
function validateForm() {
if ($('#image_file').val() === '') {
$('.error').html('Please select an image').fadeIn(500);
return false;
} else if (isError) {
return false;
} else {
return true;
}
}
$(function () {
$("#dialog").dialog({
dialogClass: 'DynamicDialogStyle',
autoOpen: false,
modal: true,
width: $(window).width()-20,
height: $(window).height()-10,
position: 'center',
buttons: {
"Uploads": function () {
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
});
function botype(a) {
if (a.options[a.selectedIndex].value === '1') {
document.getElementById('showme').style.display = 'inline-block';
}
else {
document.getElementById('showme').style.display = 'none';
}
}
Demo: Fiddle

Categories