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>
Related
Apparently this doesn't work, and since I'm new to HTML5 I'm unsure as to why. I should get some vertical lines on the canvas. The idea is to build a grid on the canvas screen to work from, but this doesn't seem to be creating the lines for some reason.
<!DOCTYPE html>
<html>
<head>
<title>Test App</title>
<style>
body {
padding:0px;
margin:0px;
}
canvas {
border:1px solid #000000;
}
</style>
</head>
<body>
<canvas id="gc" width="800" height="600"></canvas>
<script>
function buildGrid() {
alert("Start!");
var gameCanvas = document.getElementById("gc");
var ctx = gameCanvas.getContext("2d");
for (x=5; x<gameCanvas.width; x+=5) {
console.log(x);
ctx.moveTo(x, 10);
ctx.lineTo(x, gameCanvas.length);
}
ctx.strokeStyle = "black";
ctx.stroke();
}
window.onload = buildGrid();
</script>
</body>
</html>
Instead of
ctx.lineTo(x, gameCanvas.length);
Try
ctx.lineTo(x, gameCanvas.height);
https://jsfiddle.net/9as7mwb6/6/
There’s no gameCanvas.length. It should be gameCanvas.height.
However, I think you should add 0.5 to each x value in order to make the edges sharp instead of blurry:
for (var x = 5; x < gameCanvas.width; x += 5) {
console.log(x);
ctx.moveTo(x + 0.5, 10);
ctx.lineTo(x + 0.5, gameCanvas.height);
}
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>
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.
I have the following fading code which allows me to fade in the text from white to black, but on my website i have a back backround and need to fade this from black to white, can anyone help..
<html>
<head>
<title>Fading Text Example</title>
<script language="javascript">
var hcolor=255;
function Fade(direction) {
obj=document.getElementById("head1");
hcolor += direction;
if (hcolor >= 0 && hcolor < 256) {
hex=hcolor.toString(16);
if (hex.length==1) hex="0" + hex;
obj.style.color="#" + hex + hex + hex;
window.setTimeout("Fade(" + direction + ");",1);
}
}
</script>
</head>
<body onLoad="Fade(1);">
<h1 ID="head1" style="color:#FFFFFF;">
Fading Text Example</h1>
</body>
</html>
It seems the function already includes the ability to specify direction, just pass in -1 instead of 1, and set initial hColor to 0. Node that in the below I've also edited the formatting slightly to clean up variable names and make it marginally cleaner / more compliant.
<html>
<head>
<title>Fading Text Example</title>
<script language="text/javascript">
var hColor=0;
function fade(direction) {
obj=document.getElementById("head1");
hcolor += direction;
if ((hColor >= 0) && (hColor < 256)) {
hex=hColor.toString(16);
if (hex.length==1) hex="0" + hex;
obj.style.color="#" + hex + hex + hex;
window.setTimeout("fade(" + direction + ");",1);
}
}
</script>
</head>
<body onload="fade(-1);">
<h1 id="head1" style="color:#FFFFFF;">Fading Text Example</h1>
</body>
i finished my app but when i test it on the other internet browsers, there was a problem
i will add my code. i couldnt see the error.as i said it works on opera but not in firefox :/
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2011/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '199193070140222', status: true, cookie: true, xfbml: true});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/tr_TR/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}
());
function lget(idd){
FB.api('/'+idd, function(response) {
document.getElementById(idd+"_a").innerHTML ="<a href='" + response.link + "' id='"+idd+"_und' style='color:#12566C;font-size:14px;' onmouseover=document.getElementById('"+idd+"').style.textDecoration=underline; onmouseout=document.getElementById('"+idd+"').style.textDecoration=none; target='_blank'><b>" + response.name + "</b></a>";
});
}
</script>
<div style="padding-left:6px;"><center>
<div id="525864081_a" ></div>
<script type="text/javascript">
lget(525864081);
</script>
<div id="534018674_a" ></div>
<script type="text/javascript">
lget(534018674);
</script>
</div>
</body>
</html>
You are loading the Facebook JS SDK in async mode and thus the FB object is not ready when you call it inside lget, the async loading occurs after your calls to lget and even after the onload event in Firefox.
Try not loading the code asynchronously and note that it is working fine
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2011/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({appId: '199193070140222', status: true, cookie: true, xfbml: true});
function lget(idd){
FB.api('/'+idd, function(response) {
document.getElementById(idd+"_a").innerHTML ="<a href='" + response.link + "' id='"+idd+"_und' style='color:#12566C;font-size:14px;' onmouseover=document.getElementById('"+idd+"').style.textDecoration=underline; onmouseout=document.getElementById('"+idd+"').style.textDecoration=none; target='_blank'><b>" + response.name + "</b></a>";
});
}
</script>
<div style="padding-left:6px;"><center>
<div id="525864081_a" ></div>
<script type="text/javascript">
lget(525864081);
</script>
<div id="534018674_a" ></div>
<script type="text/javascript">
lget(534018674);
</script>
</div>
</body>
</html>
if you want to see the execution order try something like this
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2011/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body onload="console.log('onload event'); false;">
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '199193070140222', status: true, cookie: true, xfbml: true});
console.log('FB object ready');
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/tr_TR/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
console.log('This executed first');
}
());
function lget(idd){
console.log('lget - ' + idd);
};
</script>
<div style="padding-left:6px;"><center>
<div id="525864081_a" ></div>
<script type="text/javascript">
lget(525864081);
</script>
<div id="534018674_a" ></div>
<script type="text/javascript">
lget(534018674);
</script>
</div>
</body>
</html>
this is the output you'll get in Firefox
This executed first
lget - 525864081
lget - 534018674
onload event
FB object ready