I am using fabric.js i am trying to upload image on canvas without submit button ,image is uploading successfully but the problem is that when i upload one image its uploading 4 time's on canvas just let me know how do i break the loop once count==1
$(document).ready(function(e) {
$('#preview').bind('DOMNodeInserted DOMSubtreeModified DOMNodeRemoved', function(event) {
// alert('NotChanged');
var count=0;
var gal_id =$(this).children('img').attr('id');
if(gal_id=='upload')
{
count++;
// alert(count);
// alert(gal_src);
}
if(count==1)
{
//var gal_id =$(this).children('img').attr('id');
var imgInstance2 = new fabric.Image(gal_id, {
left: 300,
top: 200,
// height:100,
angle: 60
// opacity: 0.85
});
// add image onto canvas
canvas.add(imgInstance2);
parent.$("#upload_image_pop_up").bPopup().close();
}
})
}
You can see here one image attached 4 times.
Got the answer following is my code.
$(document).ready(function(e) {
var flag=0;
$('#preview').bind('DOMNodeInserted', function(event) {
//$('#preview').bind('DOMNodeInserted DOMSubtreeModified DOMNodeRemoved', function(event) {
if(flag==0)
{
// $('#preview').bind('DOMNodeInserted DOMSubtreeModified DOMNodeRemoved', function(event) {
// alert('NotChanged');
var count=0;
var gal_id =$(this).children('img').attr('id');
var gal_src =$(this).children('img').attr('src');
if(gal_id=='upload')
{
count++;
// alert(count);
// alert(gal_src);
}
if(count==1)
{
//var gal_id =$(this).children('img').attr('id');
var imgInstance2 = new fabric.Image(gal_id, {
left: 300,
top: 200,
// height:100,
angle: 60
// opacity: 0.85
});
// add image onto canvas
canvas.add(imgInstance2);
parent.$("#upload_image_pop_up").bPopup().close();
flag=1;
}
}
})
Related
I am struggling with the small project in which I want to add different slots and save in database.
All things are working fine as expected, I am saving the json in database and calling again on edit page.
Problem is the rectangles added by json are not draggable and not transformed.
my javascript code
var json = 'jsoncode';
// create node using json string
var stage = Konva.Node.create(json, 'canvas-container');
var layer = new Konva.Layer();
stage.add(layer);
layer.draw();
stage.on('click', function (e) {
// if click on empty area - remove all transformers
if (e.target === stage) {
stage.find('Transformer').destroy();
layer.draw();
return;
}
// do nothing if clicked NOT on our rectangles
if (!e.target.hasName('rect')) {
return;
}
// remove old transformers
// TODO: we can skip it if current rect is already selected
stage.find('Transformer').destroy();
// create new transformer
var tr = new Konva.Transformer();
layer.add(tr);
tr.attachTo(e.target);
layer.draw();
});
$("#add-shape").click(function(e){
e.preventDefault();
addShape();
});
/******** add shape *********/
var addShape = function(){
console.log("add shape");
var $i = 1;
var layer = new Konva.Layer();
var parentContainer = new Konva.Rect({
x: 30,
y: 40,
width: 200,
height: 60,
name: random_name(),
fill: random_hex_color(),
draggable: true,
stroke: '#fff',
strokeWidth: 1
});
layer.add(parentContainer);
stage.add(layer);
parentContainer.on('click',function(e){
var tr = new Konva.Transformer();
layer.add(tr);
tr.attachTo(e.target);
layer.draw();
});
/*
* dblclick to remove box for desktop app
* and dbltap to remove box for mobile app
*/
parentContainer.on("dblclick dbltap", function() {
this.destroy();
stage.find('Transformer').destroy();
layer.draw();
});
stage.on('click', function (e) {
// if click on empty area - remove all transformers
if (e.target === stage) {
stage.find('Transformer').destroy();
layer.draw();
return;
}
});
parentContainer.on("transform", function(e){
console.log('Moving ' + e.target.name());
//layer.draw();
});
parentContainer.on("dragend", function(e){
console.log('X ' + e.target.x());
//layer.draw();
});
}
In your click event listener you have the condition:
// do nothing if clicked NOT on our rectangles
if (!e.target.hasName('rect')) {
return;
}
But rectangles in your json don't have rect name. You should add this name, or remove the condition.
In the latest version of Fabric JS, image drop feature is not working as expected.
function handleDrop(e) {
e.preventDefault();
// this / e.target is current target element.
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
var obj = document.querySelector('#draggable_items_container .drag_item.draggable_items');
if($(obj).attr('data-type')=='image')
{
var image_url = $(obj).attr('data-value');
var new_image = new fabric.Image(obj, {
width: obj.width,
height: obj.height,
left: e.layerX,
top: e.layerY,
});
canvas.add(new_image);
}
else
{
var text_value = $(obj).attr('data-value');
if(text_value=='')
{
alert('You cant drag blank text');
return false;
}
var params = {
canvas_obj : canvas,
text: text_value,
left : e.layerX,
top : e.layerY,
font_size : 22,
editable: false,
};
add_text_canvas(params);
}
return false;
}
Working Fiddle:
http://jsfiddle.net/Ahammadalipk/w8kkc/185/
Not working in 2.0.0-beta.7
http://jsfiddle.net/dhavalsisodiya/w8kkc/412/
So how to fix this?
var newImage = new fabric.Image(img, {
width: img.naturalWidth,
height: img.naturalHeight,
scaleX: setImageWidth/img.naturalWidth,
scaleY: setImageHeight/img.naturalHeight,
// Set the center of the new object based on the event coordinates relative
// to the canvas container.
left: e.layerX,
top: e.layerY
});
You need to set actual width and height of image, then scale X and Y,according to your requirement. Here is updated fiddle
I uploaded some images using this Blueimp's awesome plugin JQuery File Upload.
I now want to allow my users to Resize (with a preview) and Crop and Save them using only Blueimp plugins suite.
I know these plugins JavaScript-Canvas-to-Blob, JavaScript-Load-Image. I want to use them to edit an image from the server as you can see on the below image.
var $imageWrapper = $('#imageWrapper'), currentFile,
coordinates, actionsNode = $('#actions')
replaceResults = function (img) {
var content;
if (!(img.src || img instanceof HTMLCanvasElement)) {
content = $('<span>Loading image file failed</span>');
} else {
content = $('<a target="_blank">').append(img)
.attr('download', currentFile.name)
.attr('href', img.src || img.toDataURL());
}
$('#watcher').replaceWith(content);
//console.info(content)
$imageWrapper.children().replaceWith(content);
if (img.getContext) {
actionsNode.show();
}};
$('.profile-update').click(function(event) {
event.preventDefault();
var imageUrl = app.basePath + $(this).closest('.view').find('a').attr('href');
loadImage(
imageUrl,
function(img) {
if (img.type === "error") {
app.noticeBox("Error loading the selected image");
} else {
var $cropperWrapperClone = $('#cropperWrapper').clone(true);
$imageWrapper = $cropperWrapperClone.find('#imageWrapper');
$imageWrapper.html($(img).addClass('object-border'));
app.modalBox({
content: $cropperWrapperClone
});
$('#editImage', $cropperWrapperClone).on('click', function(event) {
event.preventDefault();
var imgNode = $imageWrapper.find('img, canvas'),
img = imgNode[0];
imgNode.Jcrop({
setSelect: [0, 0, 250, 250],
onSelect: function(coords) {
coordinates = coords;
},
onRelease: function() {
coordinates = null;
}
}).parent().on('click', function(event) {
event.preventDefault();
});
});
$('#cropImage', $cropperWrapperClone).on('click', function(event) {
event.preventDefault();
var img = $imageWrapper.find('img, canvas')[0];
if (img && coordinates) {
replaceResults(loadImage.scale(img, {
left: coordinates.x,
top: coordinates.y,
sourceWidth: coordinates.w,
sourceHeight: coordinates.h,
minWidth: $imageWrapper.width()
}));
coordinates = null;
}
});
}
}, {
maxHeight: 500,
maxWidth: 600,
//aspectRatio: 16/9
}
);)};
The code above is what I have. How to be able to have a preview of the selected image and save it when user clicks on "Save" button?
I'll really appreciate you help.
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
Looking for a little help with this slider that came with a Magento Template I purchased.
I'm trying to add a pause on hover and resume on mouse out but am very new to getting my hands this dirty with the JavaScript.
Hoping for a push in the right direction
Here is the code I'm working with
function decorateSlideshow() {
var $$li = $$('#slideshow ul li');
if ($$li.length > 0) {
// reset UL's width
var ul = $$('#slideshow ul')[0];
var w = 0;
$$li.each(function(li) {
w += li.getWidth();
});
ul.setStyle({'width':w+'px'});
// private variables
var previous = $$('#slideshow a.previous')[0];
var next = $$('#slideshow a.next')[0];
var num = 1;
var width = ul.down().getWidth() * num;
var slidePeriod = 3; // seconds
var manualSliding = false;
// next slide
function nextSlide() {
new Effect.Move(ul, {
x: -width,
mode: 'relative',
queue: 'end',
duration: 1.0,
//transition: Effect.Transitions.sinoidal,
afterFinish: function() {
for (var i = 0; i < num; i++)
ul.insert({ bottom: ul.down() });
ul.setStyle('left:0');
}
});
}
// previous slide
function previousSlide() {
new Effect.Move(ul, {
x: width,
mode: 'relative',
queue: 'end',
duration: 1.0,
//transition: Effect.Transitions.sinoidal,
beforeSetup: function() {
for (var i = 0; i < num; i++)
ul.insert({ top: ul.down('li:last-child') });
ul.setStyle({'position': 'relative', 'left': -width+'px'});
}
});
}
function startSliding() {
sliding = true;
}
function stopSliding() {
sliding = false;
}
// bind next button's onlick event
next.observe('click', function(event) {
Event.stop(event);
manualSliding = true;
nextSlide();
});
// bind previous button's onclick event
previous.observe('click', function(event) {
Event.stop(event);
manualSliding = true;
previousSlide();
});
// auto run slideshow
new PeriodicalExecuter(function() {
if (!manualSliding) nextSlide();
manualSliding = false;
}, slidePeriod);
}
Now I'm guessing the best way would be to manipulate a hover or mouseover observer similar to the next and previous ones to stop and start but I'm just not sure on how to set this up.
Would appreciate a push in the right direction!
Edit ....
So I'm getting much closer but I seem to have a problem yet hopefully someone who know about prototype can help.
I got it to work by adding this variable
var stopSliding = false;
and then adding an if like so
function nextSlide() {
if (!stopSliding) {
new Effect.Move(ul, {
x: -width,
mode: 'relative',
queue: 'end',
duration: 1.0,
//transition: Effect.Transitions.sinoidal,
afterFinish: function() {
for (var i = 0; i < num; i++)
ul.insert({ bottom: ul.down() });
ul.setStyle('left:0');
}
});
}
}
// previous slide
function previousSlide() {
if (!stopSliding) {
new Effect.Move(ul, {
x: width,
mode: 'relative',
queue: 'end',
duration: 1.0,
//transition: Effect.Transitions.sinoidal,
beforeSetup: function() {
for (var i = 0; i < num; i++)
ul.insert({ top: ul.down('li:last-child') });
ul.setStyle({'position': 'relative', 'left': -width+'px'});
}
});
}
}
then
ul.observe('mouseover', function(event) {
stopSliding = true;
});
ul.observe('mouseout', function(event) {
stopSliding = false;
});
This method works but only Safari will auto start my slideshow now and firefox needs interaction to trigger a start.
However I did find that switching the var to true at the start and switching around the order of the mouseovers it then auto starts fine in Firefox and not in Safari.
Had enough for this evening.
So I managed to get it to work in both Firefox, Safari, IE etc using:
Event.observe( window, 'load', function() { stopSliding = false; });
This ensures that my variable "stopSliding" is set.