Drag and Drop Cordova Image - image

First of all, I'm using cordova.
I wanna do an application which get a picture and shows it at the screen (it's done!). Now, I need to pick some other little images, drag and drop them on the original picture, save the modifications and send to a server...
How can I do the drag and drop AND save the big image after dropped little images? (if possible, using plugins)
I saw this, but how can I save as a new image?
Drag and Drop functionality in PhoneGap?

How I did this:
HTML
<!DOCTYPE html>
<html>
<head>
<!-- meta -->
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<!-- css -->
<link rel="stylesheet" type="text/css" href="css/camera.css">
<!-- js -->
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/camera.js"></script>
<script type="text/javascript" src="js/compartilhamento.js"></script>
<!-- jQuery -->
<script type="text/javascript" src="jQuery/jquery-1.10.2.js"></script>
<!--script type="text/javascript" src="jQuery/jquery.mobile-1.4.5.min.js"></script-->
<script type="text/javascript" src="jQuery/jquery-ui.min.js"></script>
<script src="jQuery/jquery.ui.touch-punch.min.js"></script>
<!-- js drag and drop -->
<script type="text/javascript" src="js/add-aderecos.js"></script>
<script type="text/javascript" src="js/salva-canvas.js"></script>
<title></title>
</head>
<body>
<div style="" id="botoes">
<p>Voltar</p>
<p><input type="button" onClick="tiraFoto()" value="Acessar Câmera"></p>
</div>
<!--Aqui estao os objetos disponibilizados para drag-->
<div id="objetos" style="display: none;">
<p>Clique na imagem que desejar adicionar à sua foto!</p>
<img src="img/nariz.png" id="add-nariz"></img>
<hr/>
</div>
<!--Pega as dimensoes da foto vinda da camera/galeria e posteriormente é cópia do canvas, para que possa ser compartilhado via social-x-sharing plugin-->
<img id="pegaDim" src="" style="display: none;"></img>
<!--aqui está a foto tirada, com redimensionamento via CSS. Aqui acontece a edicao da imagem-->
<div id="box-foto">
<img src="" id="imagemCamera" style="display: none;"></img>
</div>
<!--pra cá será copiada a imagem editada-->
<canvas id="myCanvas" style="display: none;"></canvas>
<!--botoes-->
<div id="compartilhamento" style="display: none;">
<p><input type="button" value="Salvar Mudanças" id="salvaImagem"/></p>
<p><input type="button" onclick="imagemTeste('pegaDim');" value="Compartilhar Imagem" /></p>
</div>
</body>
</html>
camera.js
function tiraFoto() {
navigator.camera.getPicture(onSuccess, onFail,
{
destinationType : Camera.DestinationType.FILE_URI,
sourceType : Camera.PictureSourceType.CAMERA
}
);
}
function onSuccess(imageData) {
//pega DOM
var compartilha = document.getElementById('compartilhamento');
var botoes = document.getElementById('botoes');
var pegaDim = document.getElementById('pegaDim');
var image = document.getElementById('imagemCamera');
var objetos = document.getElementById('objetos');
//aparece depois da foto
objetos.style.display = 'block';
pegaDim.src = imageData;
image.src = imageData;
image.style.display = 'block';
compartilha.style.display = 'block';
botoes.style.display = 'none';
}
function onFail(message) {
alert('Erro: ' + message);
}
add-aderecos.js
$(document).on('click', '#add-nariz', function(){
var a = $('#add-nariz');
var src = a.attr('src');
var elem = $('<img class="objetos" src="' + src + '" width="30px" height="30px" style="positon: relative;" />');
$('#box-foto').append(elem);
elem.draggable();
});
salva-canvas.js
$(document).on('click', '#salvaImagem', function(){
//pega dimensoes originais da foto da camera/galeria
var dimensoesOriginais = document.getElementById('pegaDim');
var larguraOriginal = dimensoesOriginais.width;
var alturaOriginal = dimensoesOriginais.height;
//pega a imagem que aparece na tela e o canvas
var m = $('#imagemCamera');
var totX = parseInt(m.css('width'));
var totY = parseInt(m.css('height'));
var c = document.getElementById('myCanvas');
c.width = totX;
c.height = totY;
var ctx = c.getContext('2d');
//alert(totX + '\n' + totY);
var base = m[0];
//drawImage(imagem,comecaCorteX,comecaCorteY,paraCorteX,paraCorteY,X,Y,Largura,Altura)
ctx.drawImage(base,0,0,larguraOriginal,alturaOriginal,0,0,totX,totY);
var posicoes = [];
$(".objetos").each(function(){
var img = $(this);
x = parseInt(img.css("left"))+totX;
y = parseInt(img.css("top"))+totY;
altura = parseInt(img.css("width"));
largura = parseInt(img.css("height"));
posicoes.push([
x,
y,
largura,
altura,
]);
});
//alert( JSON.stringify(posicoes));
//pega a imagem do nariz -- palheativo
var copiasNariz = $('#add-nariz')[0];
//loop pra canvas
var j;
var numAderecos = posicoes.length;
for(j = 0; j < numAderecos; j++){
//drawImage(imagem,comecaCorteX,comecaCorteY,paraCorteX,paraCorteY,X,Y,Largura,Altura)
ctx.drawImage(copiasNariz,posicoes[j][0]-156+(j*posicoes[j][2]),posicoes[j][1],posicoes[j][2],posicoes[j][3]);
alert('posicao inicial: ' + posicoes[j][0] + '\n\nposicao final: ' + posicoes[j][0]-156+(j*posicoes[j][2]) + '\n\nvariacao de :' + (-156+(j*posicoes[j][2])));
}
//Esconde a foto original e mostra o canvas
var some = document.getElementById('box-foto');
c.style.display = "block";
some.style.display = "none";
//esconde os objetos arrastaveis
$('#objetos')[0].style.display = "none";
//faz uma copia do canvas como src de uma tag img -- vai pro pegaDim
var finalImageToShare = new Image();
var srcFinal = finalImageToShare.src;
srcFinal = c.toDataURL();
dimensoesOriginais.src = srcFinal;
});
compartilhamento.js
function imagemTeste(idTag) {
var tag = document.getElementById(idTag);
var img = tag.src;
window.plugins.socialsharing.share('Imagem compartilhada via aplicativo X.', 'Assunto (caso envie por email)', img, null);
}
I really sorry for the portuguese ids, classes and the names of variables or functions, but I'm afraid when I change to english forgot something and this stops working. So I copied the code as it is in my real project.
I believe my code is "ugly" and longer than necessary, but I'm not so good with javaScript yet.

Related

FireFox reports bogus event.srceenY value

Below is the most simple code to drag an element, in this case a <DIALOG>.
Works fine in latest Chrome and the likes, but not in latest Firefox.
Here it looks like the event.screenY has a positiv offset. This value is used in the onmousedown
and the ondragend functions
I assume (never assume!!) it is the height of the header holding tabs, bookmarks and the like.
Is this a defect in Firefox or what am I doing wrong. Any Ideas ?
<!DOCTYPE html>
<html>
<head>
<title>screenY test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
*{
margin:0;
padding:0
}
</style>
</head>
<body>
<dialog open id='alertDialog' >
<div class='handle'>drag me here</div>
<br>
<div id='out'>You should never see this</div>
<hr>
<button >Ok</button>
</dialog>
<script>
var obj, out = document.querySelector('#dout');
obj = document.querySelector('#alertDialog');
makedrag(obj);
function makedrag(obj) {
var han = obj.querySelector('.handle');
han.onmousedown = (e) => {// save positions at start
obj.draggable = true;
obj.hgsX = e.screenX;
obj.hgsY = e.screenY;
obj.querySelector('#out').innerText = e.screenY;
obj.hgsposX = obj.offsetLeft;
obj.hgsposY = obj.offsetTop;
};
obj.ondragend = (e) => {
var t, l;
t = e.target.offsetTop + (e.screenY - obj.hgsY);
l = e.target.offsetLeft + (e.screenX - obj.hgsX);
obj.draggable = false;
t = Math.max(0, t);
t = Math.min(t, window.innerHeight - obj.clientHeight);
l = Math.max(0, l);
l = Math.min(l, window.innerWidth - obj.clientWidth);
obj.style.top = t + 'px';
obj.style.left = l + 'px';
obj.style.position = 'fixed';
};
}
</script>
</body>
</html>

How to put data ranges in piecharts using dc.js?

I have a pie chart for age, which currently has pie slices for every age there in the data set. Since the age range is wide, numerous thin slices are formed in the pie chart. I want to make it as a range, like one slice should show 0-18, another 19-30, and so on. How can I do this?
Here is my code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="bower_components/dcjs/dc.css">
<link rel="stylesheet" href="bower_components/leaflet/dist/leaflet.css">
<script src="bower_components/d3/d3.min.js"></script>
<script src="bower_components/crossfilter2/crossfilter.min.js"></script>
<script src="bower_components/dcjs/dc.js"></script>
<!--THE FOLLOWING META IS IMPORTANT, OTHERWISE THERE MIGHT BE A PROBLEM WITH SOME CHARACTERS-->
<meta http-equiv="content-type" content="text/html; charset=UTF8">
<!--CDN FOR JQUERY-->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<div id="map">
<a class="reset" href="javascript:usChart.filterAll();dc.redrawAll();" style="display: none;">reset</a>
<span class="reset" style="display: none;"> | Current filter: <span class="filter"></span></span>
<div class="clearfix"></div>
</div>
<div id="pie-gender">
<a class="reset" href="javascript:usChart.filterAll();dc.redrawAll();" style="display: none;">reset</a>
<span class="reset" style="display: none;"> | Current filter: <span class="filter"></span></span>
<div class="clearfix"></div>
</div>
<div id="pie-age">
<a class="reset" href="javascript:usChart.filterAll();dc.redrawAll();" style="display: none;">reset</a>
<span class="reset" style="display: none;"> | Current filter: <span class="filter"></span></span>
<div class="clearfix"></div>
</div>
<div>
Reset All
</div>
<script type="text/javascript">
d3.csv("data/gender.csv", function (data) {
d3.json("data/us-states.json", function (json){
// set up crossfilter on the data.
var ndx = crossfilter(data);
// set up the dimensions
var stateDim = ndx.dimension(function (d) { return d.state; });
var genderDim = ndx.dimension(function(d) { return d.gender; });
var ageDim = ndx.dimension(function(d) { return d.age; });
//filtering age ranges
var age_0_18 = ageDim.filter([0,19]);
var age_19_30 = ageDim.filter([19,31]);
var age_31_60 = ageDim.filter([31,61]);
var age_61_101 = ageDim.filter([61,101]);
// set up the groups/values
var state = stateDim.group();
var gender = genderDim.group();
//var age = ageDim.group();
var age1 = age_0_18.group();
var age2 = age_19_30.group();
var age3 = age_31_60.group();
var age4 = age_61_101.group();
// the different charts - options are set below for each one.
var pieGender = dc.pieChart('#pie-gender');
var pieAge = dc.pieChart('#pie-age')
var usmap = dc.geoChoroplethChart("#map");
//create pie to show gender
pieGender
.width(180)
.height(180)
.radius(80)
.dimension(genderDim)
.group(gender)
.renderLabel(true)
.innerRadius(10)
.transitionDuration(500)
//.colorAccessor(function (d, i) { return d.value; });
//below is how to decide the colours for pie slices
.colors(d3.scale.ordinal().range([ '#14CAFF', '#4646FF']));
//creating pie to show age
pieAge
.width(180)
.height(180)
.radius(80)
.dimension(ageDim)
.group(age1,age2,age3,age4)
.renderLabel(true)
.innerRadius(10)
.transitionDuration(500)
.colorAccessor(function (d, i) { return d.value; });
//display US map
usmap
.width(900)
.height(500)
.dimension(stateDim)
.group(state)
.colors(["rgb(20,202,255)","rgb(70,70,255)"])
.overlayGeoJson(json.features, "name", function (d) { return d.properties.name; })
// at the end this needs to be called to actually go through and generate all the graphs on the page.
dc.renderAll();
});
});
</script>
</body>
I tried using filter and then grouping, but the result remained the same. I think the procedure is wrong maybe.
Any help would be greatly appreciated. Thanks.
I'm sure I've seen a lot of examples of this, but I couldn't find any in a quick search.
You'll want to use the group's groupValue function to put ages into the categories you want. This is exactly the same way you would round values down or do any other categorization:
var ageGroup = ageDim.group(function(v) {
if(v < 19) return "18 or under";
else if(v < 30) return "19-29";
else if(v < 30) return "30-59";
else return "over 60";
});
Note that dimension.filter() just returns the dimension and changes the filters for the entire crossfilter, so all of your groups above would be the same group, and only the last filter would take.

X axis time formatting in dc.js

I am trying to create a linear chart in d3.js where i want x-axis to be of following format "27/11 1" where 27 is date, 11 is month and 1 is hour(24 hour time). But with the code i have it looks like only hour is printing. Can someone please help me in getting the format correctly?
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF8">
<body>
<div id="task-submissions-created-at" >
<div class="reset" style="visibility: hidden;">selected: <span class="filter"></span>
reset
</div>
<div id="gender-tasks" style="width:300px; height:300px">
<div class="reset" style="visibility: hidden;">selected: <span class="filter"></span>
reset
</div>
</div>
<script type="text/javascript" src="../js/d3.js" charset="utf-8"></script>
<script type="text/javascript" src="../js/crossfilter.js"></script>
<script type="text/javascript" src="../js/dc.js"></script>
<script type="text/javascript">
//var genderChart=dc.pieChart('#gender-tasks');
var taskSubmissionsChart=dc.lineChart('#task-submissions-created-at');
var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S.%L+05:30").parse;
d3.json("../data/task_submissions.json",function(error,value){
var ndx=crossfilter(value);
value.forEach(function(d) {
d.created_at = parseDate(d.created_at);
});
var timestampDimension=ndx.dimension(function(d){
var x=d.created_at.getHours();
return x;
});
var taskSubmissionId = timestampDimension.group().reduceSum(function(d) {return d.id;});
var minDate =timestampDimension.bottom(1)[0].created_at.getHours();
var maxDate = timestampDimension.top(1)[0].created_at.getHours();
taskSubmissionsChart
.width(768)
.height(480)
//.x(d3.time.scale().domain([d3.min(data,function(d){return d.time}),d3.max(data,function(d){return d.time})]))
.x(d3.scale.linear().domain([minDate,maxDate+1]))
.interpolate('step-before')
.renderArea(true)
.brushOn(false)
.clipPadding(10)
.yAxisLabel("This is the Y Axis!")
.dimension(timestampDimension)
.group(taskSubmissionId)
.xAxis().tickFormat(function(v){
console.log("v: "+v);
return v;
});
taskSubmissionsChart.render();
});
/*
d3.json("../data/users.json", function(error,value) {
var ndx=crossfilter(value);
var runDimension = ndx.dimension(function(d) {
return d.gender;
});
var speedSumGroup = runDimension.group();
genderChart
.width(300)
.height(300)
.slicesCap(4)
.innerRadius(10)
.dimension(runDimension)
.group(speedSumGroup)
.controlsUseVisibility(true);
dc.renderAll();
});
*/
</script>
</body>
</html>

HTML5 Image Viewer (Browse Add Image)

http://jsfiddle.net/KFEAC/2/
I'd like to learn how to add a image from my hard drive into an HTML5 canvas. I don't wanna upload it, just load it from my hard drive dynamically from a browse window after a button is clicked.
I do believe this is possible without PHP.
Can anyone help?
HTML:
<input type="file" id="openimg"> <input type="button" id="load" value="Load" style="width:100px;"><br/>
Width and Height (px): <input type="text" id="width" style="width:100px;">, <input type="text" id="height" style="width:100px;"><br/>
<canvas id="myimg" width="300" height="300"></canvas>
JavaScript/JQuery:
$(function(){
$("canvas#myimg").draggable();
var canvas = document.getElementById("myimg");
var context = canvas.getContext("2d");
function draw() {
var chosenimg = $("#openimg").val();
var w = parseInt($("#width").val());
var h = parseInt($("#height").val());
canvas.width = w;
canvas.height = h;
var img = new Image();
img.onload = function () {
context.drawImage(img,0,0,img.width,img.height,0,0,w,h);
}
img.src = $("#openimg").val();}
$("#width").val(150);
$("#height").val(150);
$("#load").click(function(){ draw(); });
});
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas = document.getElementById("myimg");
var context = canvas.getContext("2d");
function draw() {
var chosenimg = $("#openimg").val();
var w = parseInt($("#width").val());
var h = parseInt($("#height").val());
canvas.width = w;
canvas.height = h;
var img = new Image();
img.onload = function () {
context.drawImage(img,0,0,img.width,img.height,0,0,w,h);
console.log(img.src);
}
img.src = $("#openimg").val();
}
$("#width").val(150);
$("#height").val(150);
$("#load").click(function(){ draw(); });
}); // end $(function(){});
</script>
</head>
<body>
<input type="file" id="openimg">
<input type="button" id="load" value="Load" style="width:100px;"><br/>
Width and Height (px):
<input type="text" id="width" style="width:100px;">,
<input type="text" id="height" style="width:100px;"><br/>
<canvas id="myimg" width="300" height="300"></canvas>
</body>
</html>

get viewdatadictionary value in partial view

I have a partial view in which I am trying to get the values from the parent view.
This is what I am trying:
#Html.Partial("Shared", "Home", new ViewDataDictionary { { "9595959", "8sd8sds8das8d" } })
And this is the partial view:
<!-- Google Code for apply Conversion Page --> <script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = "viewdata-number1";
var google_conversion_language = "en";
var google_conversion_format = "2";
var google_conversion_color = "ffffff";
var google_conversion_label = "viewdata-number2"; var google_conversion_value = 0;
/* ]]> */
</script>
<script type="text/javascript"
src="https://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt=""
src="https://www.googleadservices.com/pagead/conversion/viewdata-number1/?value=0&label=viewdata-number2&guid=ON&script=0"/>
</div>
</noscript>
Is it possible to get the value straight away? I don't have any model or controller assigned to the partial view.
Thx in advance, Laziale
Updated Code:
#{
var variable = ViewData["First"];
<!-- Google Code for apply Conversion Page --> <script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = variable;
var google_conversion_language = "en";
var google_conversion_format = "2";
var google_conversion_color = "ffffff";
var google_conversion_label = "f6vICKTT6gMQzNOf3gM"; var google_conversion_value = 0;
/* ]]> */
</script>
<script type="text/javascript"
src="https://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt=""
src="https://www.googleadservices.com/pagead/conversion/1002957260/?value=0&label=f6vICKTT6gMQzNOf3gM&guid=ON&script=0"/>
</div>
</noscript>
}
You think that will work?
Sorry i don't understan your question quite well. You can get ViewData values in partial like this:
var a = (int)ViewData["9595959"]; // variable a will get value "8sd8sds8das8d"
You can also create new ViewDataDictionary extending current view ViewDataDictionary like this:
#Html.Partial("Shared", "Home", new ViewDataDictionary(ViewData) { { "9595959", "8sd8sds8das8d" } })
it will work like this:
#{
var variable = (int)ViewData["First"];
}
<!-- Google Code for apply Conversion Page --> <script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = #variable;
var google_conversion_language = "en";
var google_conversion_format = "2";
var google_conversion_color = "ffffff";
var google_conversion_label = "f6vICKTT6gMQzNOf3gM"; var google_conversion_value = 0;
/* ]]> */
</script>
<script type="text/javascript" src="https://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt=""
src="https://www.googleadservices.com/pagead/conversion/1002957260/?value=0&label=f6vICKTT6gMQzNOf3gM&guid=ON&script=0"/>
</div>
</noscript>
link
Here is an example of someone doing the same thing I think you're wanting to do.
Also, within your partial, just do ViewData["9595959"] to hook into that specific data.

Resources