2 self-invoking javascript functions running - javascript

I have a container which contains a primary image and 2-3 thumbnails each. I wanted the user to be able to change the image by clicking on the thumbnail of its parent. Aside from that, I want the containers to be draggable/sortable so that users can be able to compare them easily.
This is why I made these 2 self invoking functions in my javascript file.
This one is to change the primary image into the image of the thumbnail.
$(document).ready(function(){
$('.thumb-img').on('click', function(){
var url = $(this).attr('src');
$(this).closest('.item-container').find('.primary-img').attr('src', url);
});
});
While this one is used to drag and drop the containers to interchange positions.
(function() {
"use strict";
var dragAndDropModule = function(draggableElements){
var elemYoureDragging = null
, dataString = 'text/html'
, elementDragged = null
, draggableElementArray = Array.prototype.slice.call(draggableElements) //Turn NodeList into array
, dragonDrop = {}; //Put all our methods in a lovely object
// Change the dataString type since IE doesn't support setData and getData correctly.
dragonDrop.changeDataStringForIe = (function () {
var userAgent = window.navigator.userAgent,
msie = userAgent.indexOf('MSIE '), //Detect IE
trident = userAgent.indexOf('Trident/'); //Detect IE 11
if (msie > 0 || trident > 0) {
dataString = 'Text';
return true;
} else {
return false;
}
})();
dragonDrop.bindDragAndDropAbilities = function(elem) {
elem.setAttribute('draggable', 'true');
elem.addEventListener('dragstart', dragonDrop.handleDragStartMove, false);
elem.addEventListener('dragenter', dragonDrop.handleDragEnter, false);
elem.addEventListener('dragover', dragonDrop.handleDragOver, false);
elem.addEventListener('dragleave', dragonDrop.handleDragLeave, false);
elem.addEventListener('drop', dragonDrop.handleDrop, false);
elem.addEventListener('dragend', dragonDrop.handleDragEnd, false);
};
dragonDrop.handleDragStartMove = function(e) {
var dragImg = document.createElement("img");
dragImg.src = "http://alexhays.com/i/long%20umbrella%20goerge%20bush.jpeg";
elementDragged = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData(dataString, this.innerHTML);
//e.dataTransfer.setDragImage(dragImg, 20, 50); //idk about a drag image
};
dragonDrop.handleDragEnter = function(e) {
if(elementDragged !== this) {
this.style.border = "2px dashed #3a3a3a";
}
};
dragonDrop.handleDragOver = function(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
};
dragonDrop.handleDragLeave = function(e) {
this.style.border = "2px solid transparent";
};
dragonDrop.handleDrop = function(e) {
if(elementDragged !== this) {
var data = e.dataTransfer.getData(dataString);
elementDragged.innerHTML = this.innerHTML;
this.innerHTML = e.dataTransfer.getData(dataString);
}
this.style.border = "2px solid transparent";
e.stopPropagation();
return false;
};
dragonDrop.handleDragEnd = function(e) {
this.style.border = "2px solid transparent";
};
// Actiavte Drag and Dropping on whatever element
draggableElementArray.forEach(dragonDrop.bindDragAndDropAbilities);
};
var allDraggableElements = document.querySelectorAll('.draggable-droppable');
dragAndDropModule(allDraggableElements);
})();
The two functions work but when I drag the container and change its position, the first function doesn't work anymore.

It's probably because you drag it and recreate the element node.
you can use Event to solve the problem.
$(document).ready(function(){
// It delegate thumb-img event to body, so whatever you recreate thumb-img,is all right
$('body').on('click', '.thumb-img', function(){
var url = $(this).attr('src');
$(this).closest('.item-container').find('.primary-img').attr('src', url);
});
});

Related

Not being able to Load Image from a function To HTML Canvas

I am trying to place the screenshot image into html canvas but not being able to. I have taken screenshot of current tab by using following chrome API. Trying to make a chrome extension.
/* background.js */
let id = 100;
//calling chrome api
chrome.browserAction.onClicked.addListener(() => {
chrome.tabs.captureVisibleTab((screenshotUrl) => {
const viewTabUrl = chrome.extension.getURL('screenshot.html?id=' + id++)
let targetId = null;
//checking if the opened tab id is the same as the target id
chrome.tabs.onUpdated.addListener(function listener(tabId, changedProps) {
if (tabId != targetId || changedProps.status != "complete")
return;
chrome.tabs.onUpdated.removeListener(listener);
const views = chrome.extension.getViews();
for (let i = 0; i < views.length; i++) {
let view = views[i];
if (view.location.href == viewTabUrl) {
view.setScreenshotUrl(screenshotUrl);
return;
}
}
});
//chrome tabs create method
//no listener on create event because the tab’s URL may not be set at the time this event is fired
chrome.tabs.create({ url: viewTabUrl }, (tab) => {
targetId = tab.id;
});
});
});
But not able to call the image from the function
function setScreenshotUrl(url) {
document.getElementById('target').src = url;
};
var cnv = document.getElementById("conv");
cnv.onclick = function() {
var x = document.getElementById("target").src;
document.getElementById("demo").innerHTML = x;
};
window.addEventListener('load', function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("target");
ctx.drawImage(img, 10, 10, 300, 175, 0, 0, 100, 175);
});
The problem was image was not ready at windows on load event, verified by checking the innerHTML of the image, while if I try to do the same thing in onClick event, the image is successfully loaded into canvas.

javascript audio gets lauder each click

I was implementing some audio files today in my Javascript and it works fine. But
I noticed that with each subsequent click the sound gets louder. I alreadio used the "Audio.volume" method but no luck.
My Code:
var AppController = (function () {
var correctItem, secondItem, thirdItem, selectedItems, selectedItemsShuffled;
var rotateImage = function() {
var i = 0;
var randomNumbers = createThreeRandomNumbers();
var interval = window.setInterval(function () {
i++;
document.getElementById("imageToRotate").src= "img/" + items.images[i].imageLink;
if (i === items.images.length -1) {
i = -1;
}
}, 125);
var clearData = function () {
correctItem = "";
secondItem = "";
thirdItem = "";
selectedItems = "";
selectedItemsShuffled = "";
removeNodeChildren("button-1");
removeNodeChildren("button-2");
removeNodeChildren("button-3");
};
var removeNodeChildren = function (obj) {
var myNode = document.getElementById(obj);
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
};
var resetGame = function () {
clearData();
document.getElementById("buttonWrapper").classList.remove("show");
rotateImage();
}
document.getElementById("imageToRotate").addEventListener("click", function (e) {
// select 3 items
correctItem = getSelectedItemDetails(e);
secondItem = getRandomItem(correctItem);
thirdItem = getSecondRandomItem(correctItem, secondItem);
selectedItems = [correctItem, secondItem, thirdItem];
selectedItemsShuffled = shuffleArray(selectedItems);
// create the numbers 1 to 3 randomly
var order = createThreeRandomNumbers();
// remove the rotating effect
clearInterval(interval);
// set the images to the buttons in a random order.
setItemsToButtons(order, selectedItemsShuffled);
//show the buttons
showButtons();
// Create an event which triggers when a button is clicked.
document.getElementById("buttonWrapper").addEventListener("click", function(e) {
var valueOfButtonPressed = e.srcElement.innerText.toLowerCase();
var clickedButton = e.srcElement.id;
if (valueOfButtonPressed === correctItem) {
document.getElementById(clickedButton).innerHTML = e.srcElement.innerText.toLowerCase() + '<span class="icon"><i class="fa fa-check green" aria-hidden="true"></i></span>';
if (!audio) {
var audio = new Audio("audio/correct.mp3");
}
audio.play();
audio.volume = 0.5;
setTimeout(resetGame, 5000);
} else {
document.getElementById(clickedButton).innerHTML = e.srcElement.innerText.toLowerCase() + '<span class="icon"><i class="fa fa-times red" aria-hidden="true"></i></span>';
if (!audio) {
var audio = new Audio("audio/wrong.mp3");
}
audio.play();
audio.volume = 0.5;
setTimeout(resetGame, 5000);
}
});
});
};
// 1: hide the buttons
hidebuttons();
// 2: Replace the title
replaceTitle("Animals");
// 3: set up image rotation until it's clicked.
rotateImage();
})();
Any help will be much appreciated. Cheers!
I'm fairly certain the reason is that you're making a new Audio object with every single click.
Instead of doing this with every click:
var audio = new Audio("audio/correct.mp3");
do a check to see if audio already exists. if it does, then simply do audio.play(). If it does not, THEN you make a new audio object.

How to remove added template from canvas in fabricjs?

I need to remove added template from canvas when I insert a layout. I use following code to clear canvas but it does not work.
function clearCanvas() {
canvas.clear();
canvas.renderAll.bind(canvas);
$('#layer-list li').each(function(i,obj) {
if(!$(this).hasClass('disabled'))
$(this).remove();
});
}
Layout adding function as follows.
$(document).on('click','#layout-content .item', function(event) {
if($(this).attr('data-image')) {
var url = $(this).attr('data-image');
if(url != '') {
layoutMode = true;
clearCanvas();
loadLayout(url);
}
}
});
Loadlayout function
function loadTemplate(url) {
fabric.loadSVGFromURL(url, function(objects, options) {
var svg = fabric.util.groupSVGElements(objects,options);
svg.scaleToHeight(canvas.getHeight());
canvas.add(svg);
svg.center();
canvas.renderAll();
var bounds = svg.getObjects();
fabric.loadSVGFromURL(url, function(objects, options) {
var group = new fabric.Group(objects,options);
canvas.add(group);
group.scaleToHeight(canvas.getHeight());
canvas.renderAll();
var items = group._objects;
group._restoreObjectsState();
canvas.remove(group);
for(var i = 0; i < items.length; i++) {
var left = svg.getLeft() + bounds[i].getLeft()*svg.getScaleX();
var top = svg.getTop() + bounds[i].getTop()*svg.getScaleY();
items[i].set({
left:left,
top:top,
droppable:true,
selectable:false,
hasControls:false,
hasBorders:false,
layering:false
});
canvas.add(items[i]);
canvas.renderAll();
}
canvas.remove(svg);
makeOverlay(templateBase);//////////wrong
makeOverlay(templateText);
canvas.renderAll();
});
});
}
How to fix that issue?
There are no any problems with your function clearCanvas() and $(document).on('click','#layout-content .item', function(event). The problem is in your function loadTemplate(url).
makeOverlay(templateBase);
makeOverlay(templateText);
Above line in function loadTemplate(url) load previous base template as well. So remove those lines and try.

Javascript jQuery plugin - multiple instances, external control

I am trying to wrap a canvas function in a jquery plugin, so that it can be invoked via multiple instances.
I want to be able to loop through found items and call the plugin like this
http://jsfiddle.net/M99EY/69/
HTML...
<div id="select1" class="foo" data-init="multi">A</div>
<div id="select2" class="foo" data-init="multi">B</div>
<div id="select3" class="foo" data-init="multi">C</div>
<div id="select4" class="foo" data-init="multi">D</div>
JS
...
var complicatedObj = {
init: function(element){
this.el = element;
console.log("init method", this.el);
//start a complicated process
//like rendering a canvas applicaation
this.bindEvent();
this.addRandom(this.el);
},
addRandom: function(el){
$(el).text(Math.random());
},
reInit: function(){
console.log("re-initialize method");
},
bindEvent: function(){
$(this.el).click(function() {
console.log("Letter.", $(this).text());
});
}
}
//An application with complicated functions -- initialize, re-initialize
$.multiInstance = {
id: 'multiInstance',
version: '1.0',
defaults: { // default settings
foo: 'bar'
}
};
(function ($) {
//Attach this new method to jQuery
$.fn.extend({
multiInstance: function (params) {
//Merge default and user parameters
var otherGeneralVars = 'example';
return this.each(function () {
var $this = $(this), opts = $.extend({},$.multiInstance.defaults, params);
switch (params) {
case "init":
complicatedObj.init($this);
break;
case "reInit":
complicatedObj.addRandom($this);
break;
}
//console.log("$this", $this);
console.log("params", params);
//$this.text(opts.foo);
});
}
})
})(jQuery);
/*
$("#select1").multiInstance();
$("#select2").multiInstance({foo:"foobar"})
$("#select3").multiInstance("init");*/
$('[data-init="multi"]').each(function( index ) {
//console.log( index + ": " + $( this ).text());
$(this).multiInstance("init");
});
setTimeout(function(){ $('#select3').multiInstance("reInit"); }, 2000);
but I need to be able to invoke different methods, pass arguments to these methods -- and then when a change has occurred - provide a callback to catch changes to the instance
Is this the correct way of building the plugin... I want to be able to create multiple instances of the app -- but also control it externally - and also pull values out of it for external results.
This is the application I am trying to wrap into its own jquery plugin.
https://jsfiddle.net/7a4738jo/10/
css..
body {
background-color: #CCCCCC;
margin: 0;
padding: 0;
overflow: hidden;
}
canvas{
background: grey;
}
html..
<script type="text/javascript" src="https://code.createjs.com/easeljs-0.6.0.min.js"></script>
<canvas id='canvas1' data-init="canvas360" width="465" height="465"></canvas>
<canvas id='canvas2' data-init="canvas360" width="465" height="465"></canvas>
js...
var stage;
function init(element) {
var canvas = $(element)[0];
if (!canvas || !canvas.getContext) return;
stage = new createjs.Stage(canvas);
stage.enableMouseOver(true);
stage.mouseMoveOutside = true;
createjs.Touch.enable(stage);
var imgList = ["http://jsrun.it/assets/N/b/D/X/NbDXj.jpg",
"http://jsrun.it/assets/f/K/7/y/fK7yE.jpg",
"http://jsrun.it/assets/j/U/q/d/jUqdG.jpg",
"http://jsrun.it/assets/q/o/4/j/qo4jP.jpg",
"http://jsrun.it/assets/i/Q/e/1/iQe1f.jpg",
"http://jsrun.it/assets/5/k/y/R/5kyRi.jpg",
"http://jsrun.it/assets/x/T/I/h/xTIhA.jpg",
"http://jsrun.it/assets/4/X/G/F/4XGFt.jpg",
"http://jsrun.it/assets/6/7/n/r/67nrO.jpg",
"http://jsrun.it/assets/k/i/r/8/kir8T.jpg",
"http://jsrun.it/assets/2/3/F/q/23Fqt.jpg",
"http://jsrun.it/assets/c/l/d/5/cld59.jpg",
"http://jsrun.it/assets/e/J/O/f/eJOf1.jpg",
"http://jsrun.it/assets/o/j/Z/x/ojZx4.jpg",
"http://jsrun.it/assets/w/K/2/m/wK2m3.jpg",
"http://jsrun.it/assets/w/K/2/m/wK2m3.jpg",
"http://jsrun.it/assets/4/b/g/V/4bgVf.jpg",
"http://jsrun.it/assets/4/m/1/8/4m18z.jpg",
"http://jsrun.it/assets/4/w/b/F/4wbFX.jpg",
"http://jsrun.it/assets/4/k/T/G/4kTGQ.jpg",
"http://jsrun.it/assets/s/n/C/r/snCrr.jpg",
"http://jsrun.it/assets/7/f/H/u/7fHuI.jpg",
"http://jsrun.it/assets/v/S/d/F/vSdFm.jpg",
"http://jsrun.it/assets/m/g/c/S/mgcSp.jpg",
"http://jsrun.it/assets/t/L/t/P/tLtPF.jpg",
"http://jsrun.it/assets/j/7/e/H/j7eHx.jpg",
"http://jsrun.it/assets/m/o/8/I/mo8Ij.jpg",
"http://jsrun.it/assets/n/P/7/h/nP7ht.jpg",
"http://jsrun.it/assets/z/f/K/S/zfKSP.jpg",
"http://jsrun.it/assets/2/3/4/U/234U6.jpg",
"http://jsrun.it/assets/d/Z/y/m/dZymk.jpg"];
var images = [], loaded = 0, currentFrame = 0, totalFrames = imgList.length;
var rotate360Interval, start_x;
var bg = new createjs.Shape();
stage.addChild(bg);
var bmp = new createjs.Bitmap();
stage.addChild(bmp);
var myTxt = new createjs.Text("HTC One", '24px Ubuntu', "#ffffff");
myTxt.x = myTxt.y =20;
myTxt.alpha = 0.08;
stage.addChild(myTxt);
function load360Image() {
var img = new Image();
img.src = imgList[loaded];
img.onload = img360Loaded;
images[loaded] = img;
}
function img360Loaded(event) {
loaded++;
bg.graphics.clear()
bg.graphics.beginFill("#222").drawRect(0,0,stage.canvas.width * loaded/totalFrames, stage.canvas.height);
bg.graphics.endFill();
if(loaded==totalFrames) start360();
else load360Image();
}
function start360() {
document.body.style.cursor='none';
// 360 icon
var iconImage = new Image();
iconImage.src = "http://jsrun.it/assets/y/n/D/c/ynDcT.png";
iconImage.onload = iconLoaded;
// update-draw
update360(0);
// first rotation
rotate360Interval = setInterval(function(){ if(currentFrame===totalFrames-1) { clearInterval(rotate360Interval); addNavigation(); } update360(1); }, 25);
}
function iconLoaded(event) {
var iconBmp = new createjs.Bitmap();
iconBmp.image = event.target;
iconBmp.x = 20;
iconBmp.y = canvas.height - iconBmp.image.height - 20;
stage.addChild(iconBmp);
}
function update360(dir) {
currentFrame+=dir;
if(currentFrame<0) currentFrame = totalFrames-1;
else if(currentFrame>totalFrames-1) currentFrame = 0;
bmp.image = images[currentFrame];
}
//-------------------------------
function addNavigation() {
stage.onMouseOver = mouseOver;
stage.onMouseDown = mousePressed;
document.body.style.cursor='auto';
}
function mouseOver(event) {
document.body.style.cursor='pointer';
}
function mousePressed(event) {
start_x = event.rawX;
stage.onMouseMove = mouseMoved;
stage.onMouseUp = mouseUp;
document.body.style.cursor='w-resize';
}
function mouseMoved(event) {
var dx = event.rawX - start_x;
var abs_dx = Math.abs(dx);
if(abs_dx>5) {
update360(dx/abs_dx);
start_x = event.rawX;
}
}
function mouseUp(event) {
stage.onMouseMove = null;
stage.onMouseUp = null;
document.body.style.cursor='pointer';
}
function handleTick() {
stage.update();
}
document.body.style.cursor='progress';
load360Image();
// TICKER
createjs.Ticker.addEventListener("tick", handleTick);
createjs.Ticker.setFPS(60);
createjs.Ticker.useRAF = true;
}
// Init
$(document).ready(function() {
//create multiple instances of canvas
$('[data-init="canvas360"]').each(function(index) {
init(this);
});
});

Firefox drag and drop redirect stop JQUERY

I am using fabric.js library to create a drag and drop moodboard creator. Everything works perfect, except in Firefox when I drag and drop the image to the canvas. It adds the image, but redirects to the img url. After the redirect, When I click on the back btn it goes back to the previous page and the image is on the canvas.
I have been searching and reading for a few hours now, trying all kinds of things. It seems that something in my code is preventing either "e.stopPropagation();" or "e.preventDefault()" from functioning correctly. I just cant seem to find the gremlin.
Any help would be great. Thanks!
UPDATE: Added JSFiddle.
here is a jsfiddle with my code:
http://jsfiddle.net/bQxMu/
UPDATE 2:
Fixed the issue, here is the part that fixed it:
function handleDrop(e) {
// this / e.target is current target element.
/*
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
*/
e.stopPropagation(); // Stops some browsers from redirecting.
e.preventDefault(); // Stops some browsers from redirecting.
var img = document.querySelector('#images img.img_dragging');
console.log('event: ', e);
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
// Set the center of the new object based on the event coordinates relative
// to the canvas container.
left: e.layerX,
top: e.layerY
});
canvas.add(newImage);
return false;
}
Thanks for all the help :)
window.onload=function(){
var canvas = new fabric.Canvas('canvas');
canvas.backgroundColor = '#ffffff';
function handleDragStart(e) {
[].forEach.call(images, function (img) {
img.classList.remove('img_dragging');
});
this.classList.add('img_dragging');
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
e.dataTransfer.dropEffect = 'copy';
return false;
}
function handleDragEnter(e) {
// this / e.target is the current hover target.
this.classList.add('over');
}
function handleDragLeave(e) {
e.stopPropagation();
this.classList.remove('over'); // this / e.target is previous target element.
}
function handleDrop(e) {
// this / e.target is current target element.
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
var img = document.querySelector('#images img.img_dragging');
console.log('event: ', e);
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
// Set the center of the new object based on the event coordinates relative
// to the canvas container.
left: e.layerX,
top: e.layerY
});
canvas.add(newImage);
return false;
}
function handleDragEnd(e) {
// this/e.target is the source node.
[].forEach.call(images, function (img) {
img.classList.remove('img_dragging');
});
}
var removeSelectedEl = document.getElementById('remove-selected');
removeSelectedEl.onclick = function() {
var activeObject = canvas.getActiveObject(),
activeGroup = canvas.getActiveGroup();
if (activeGroup) {
var objectsInGroup = activeGroup.getObjects();
canvas.discardActiveGroup();
objectsInGroup.forEach(function(object) {
canvas.remove(object);
});
}
else if (activeObject) {
canvas.remove(activeObject);
$("#imageControl").fadeOut('slow');
}
};
var sendBackwardsEl = document.getElementById('send-backwards');
sendBackwardsEl.onclick = function() {
var activeObject = canvas.getActiveObject();
if (activeObject) {
canvas.sendBackwards(activeObject);
}
};
var sendToBackEl = document.getElementById('send-to-back');
sendToBackEl.onclick = function() {
var activeObject = canvas.getActiveObject();
if (activeObject) {
canvas.sendToBack(activeObject);
}
};
var bringForwardEl = document.getElementById('bring-forward');
bringForwardEl.onclick = function() {
var activeObject = canvas.getActiveObject();
if (activeObject) {
canvas.bringForward(activeObject);
}
};
var bringToFrontEl = document.getElementById('bring-to-front');
bringToFrontEl.onclick = function() {
var activeObject = canvas.getActiveObject();
if (activeObject) {
canvas.bringToFront(activeObject);
}
};
document.getElementById('saveImg').onclick = function() {
if (!fabric.Canvas.supports('toDataURL')) {
alert('This browser doesn\'t provide means to serialize canvas to an image');
}
else {
canvas.deactivateAll().renderAll();
window.open(canvas.toDataURL('png'));
}
};
canvas.on('selection:cleared', function(options) {
var activeObject = canvas.getActiveObject();
if (activeObject === null) {
$("#imageControl").fadeOut('slow');
}
});
canvas.on('object:selected', function(options) {
var activeObject = canvas.getActiveObject();
if (options.target && activeObject !== null) {
$("#imageControl").show('slow');
}
});
canvas.on('selection:created', function(options) {
if (options.target) {
$("#imageControl").show('slow');
}
});
if (Modernizr.draganddrop) {
// Browser supports HTML5 DnD.
// Bind the event listeners for the image elements
var images = document.querySelectorAll('#images img');
[].forEach.call(images, function (img) {
img.addEventListener('dragstart', handleDragStart, false);
img.addEventListener('dragend', handleDragEnd, false);
});
// Bind the event listeners for the canvas
var canvasContainer = document.getElementById('canvas-container');
canvasContainer.addEventListener('dragenter', handleDragEnter, false);
canvasContainer.addEventListener('dragover', handleDragOver, false);
canvasContainer.addEventListener('dragleave', handleDragLeave, false);
canvasContainer.addEventListener('drop', handleDrop, false);
} else {
// Replace with a fallback to a library solution.
alert("This browser doesn't support the HTML5 Drag and Drop API.");
}
}
HTML:
<div id="images">
<img draggable="true" src="http://i.imgur.com/q9aLMza.png" width="70" height="90"></img>
</div>
<div id="canvas-container-controls">
<div id="imageControlWrapper">
<div id="imageControl">
<button class= "imgBtn" id="saveImg">Save Canvas</button>
<button class="imgBtn" id="remove-selected">Remove selected object/group</button>
<button id="send-backwards" class="imgBtn">Send backwards</button>
<button id="send-to-back" class="imgBtn">Send to back</button>
<button id="bring-forward" class="imgBtn">Bring forwards</button>
<button id="bring-to-front" class="imgBtn">Bring to front</button>
</div>
</div>
<div id="canvas-container">
<canvas id="canvas" width="400" height="400"></canvas>
</div>
</div>
Add an e.preventDefault() in handleDrop: http://jsfiddle.net/wN29y/
function handleDrop(e) {
// this / e.target is current target element.
e.preventDefault();
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
var img = document.querySelector('#images img.img_dragging');
console.log('event: ', e);
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
// Set the center of the new object based on the event coordinates relative
// to the canvas container.
left: e.layerX,
top: e.layerY
});
canvas.add(newImage);
return false;
}
My understanding is that you should have e.stopPropagation in handleDragOver, otherwise the browser still accepts the event, and opens the image.
(Similar to my answer here: Why can't I get file dropping to work with jquery?)

Categories

Resources