Custom div draggable function - window boundaries? - javascript

I am using the following function to drag a div by a handle:
function enableDragging(ele) {
var dragging = dragging || false,
x, y, Ox, Oy,
current;
enableDragging.z = enableDragging.z || 1;
var grabber = document.getElementById("wrapId");
grabber.onmousedown = function (ev) {
ev = ev || window.event;
var target = ev.target || ev.srcElement;
current = target.parentNode;
dragging = true;
x = ev.clientX;
y = ev.clientY;
Ox = current.offsetLeft;
Oy = current.offsetTop;
current.style.zIndex = ++enableDragging.z;
document.onmousemove = function (ev) {
ev = ev || window.event;
pauseEvent(ev);
if (dragging == true) {
var Sx = ev.clientX - x + Ox,
Sy = ev.clientY - y + Oy;
current.style.left = Math.max(Sx, Math.min(document.body.offsetWidth - Sx, 0)) + "px";
current.style.top = Math.max(Sy, Math.min(document.body.offsetHeight - Sy, 0)) + "px";
document.body.focus();
document.onselectstart = function () {
return false;
};
ev.ondragstart = function () {
return false;
};
document.body.style.MozUserSelect = "none";
document.body.style.cursor = "default";
return false;
}
}
document.ondragstart = function () {
return false;
}
document.onmouseup = function (ev) {
ev = ev || window.event;
dragging && (dragging = false);
if (ev.preventDefault) {
ev.preventDefault();
} else {
e.cancelBubble = true;
e.returnValue = false;
}
document.body.style.MozUserSelect = "text";
document.body.style.cursor = "default";
//toggleEnableSelectStart(true);
return false;
}
};
}
I am trying to set boundaries to that the div cannot be dragged outside of the bounds of the actual browser window.
The above function accomplished 50% of this, it wont let the user drag the div outside of the top left and left bounds. However it left the user drag it outside bottom and right..
Any ideas how to fix this?

Take the minimum between the value you had calculated with the width/ height boundaries of the window minus the width of/height of the div:
current.style.left = Math.min(Math.max(Sx, Math.min(document.body.offsetWidth - Sx, 0)), document.body.offsetWidth - current.offsetWidth) + "px";
current.style.top = Math.min(Math.max(Sy, Math.min(document.body.offsetHeight - Sy, 0)), document.body.offsetHeight - current.offsetHeight) + "px";
edit:
Something along these lines (mind, this is quickly written, not in the same format as yours!)
http://jsfiddle.net/WKLa7/1/

Related

Extend javascript to use multiple canvas boxes

I have very little knowledge of javascript, sadly. I'm at the moment working on a script. I want to sign files online, possible with any kind of touchscreen. I've got a script online that delivers a little canvas box with signing-functionality. Sadly my javascript skills are too bad to use it the way I want.
var isSign = false;
var leftMButtonDown = false;
jQuery(function(){
//Initialize sign pad
init_Sign_Canvas();
});
function fun_submit() {
if(isSign) {
var canvas = $("#canvas").get(0);
var imgData = canvas.toDataURL();
jQuery('#page').find('p').remove();
jQuery('#page').find('img').remove();
jQuery('#page').append(jQuery('<p>Your Sign:</p>'));
jQuery('#page').append($('<img/>').attr('src',imgData));
closePopUp();
} else {
alert('Please sign');
}
}
function closePopUp() {
jQuery('#divPopUpSignContract').popup('close');
jQuery('#divPopUpSignContract').popup('close');
}
function init_Sign_Canvas() {
isSign = false;
leftMButtonDown = false;
//Set Canvas width
var sizedWindowWidth = $(window).width();
if(sizedWindowWidth > 700)
sizedWindowWidth = $(window).width() / 2;
else if(sizedWindowWidth > 400)
sizedWindowWidth = sizedWindowWidth - 100;
else
sizedWindowWidth = sizedWindowWidth - 50;
$("#canvas").width(200);
$("#canvas").height(50);
$("#canvas").css("border","1px solid #000");
var canvas = $("#canvas").get(0);
canvasContext = canvas.getContext('2d');
if(canvasContext)
{
canvasContext.canvas.width = 200;
canvasContext.canvas.height = 50;
canvasContext.fillStyle = "#fff";
canvasContext.fillRect(0,0,sizedWindowWidth,200);
canvasContext.moveTo(50,150);
canvasContext.lineTo(sizedWindowWidth-50,150);
canvasContext.stroke();
canvasContext.fillStyle = "#000";
canvasContext.font="20px Arial";
canvasContext.fillText("x",40,155);
}
// Bind Mouse events
$(canvas).on('mousedown', function (e) {
if(e.which === 1) {
leftMButtonDown = true;
canvasContext.fillStyle = "#000";
var x = e.pageX - $(e.target).offset().left;
var y = e.pageY - $(e.target).offset().top;
canvasContext.moveTo(x, y);
}
e.preventDefault();
return false;
});
$(canvas).on('mouseup', function (e) {
if(leftMButtonDown && e.which === 1) {
leftMButtonDown = false;
isSign = true;
}
e.preventDefault();
return false;
});
// draw a line from the last point to this one
$(canvas).on('mousemove', function (e) {
if(leftMButtonDown == true) {
canvasContext.fillStyle = "#000";
var x = e.pageX - $(e.target).offset().left;
var y = e.pageY - $(e.target).offset().top;
canvasContext.lineTo(x,y);
canvasContext.stroke();
}
e.preventDefault();
return false;
});
//bind touch events
$(canvas).on('touchstart', function (e) {
leftMButtonDown = true;
canvasContext.fillStyle = "#000";
var t = e.originalEvent.touches[0];
var x = t.pageX - $(e.target).offset().left;
var y = t.pageY - $(e.target).offset().top;
canvasContext.moveTo(x, y);
e.preventDefault();
return false;
});
$(canvas).on('touchmove', function (e) {
canvasContext.fillStyle = "#000";
var t = e.originalEvent.touches[0];
var x = t.pageX - $(e.target).offset().left;
var y = t.pageY - $(e.target).offset().top;
canvasContext.lineTo(x,y);
canvasContext.stroke();
e.preventDefault();
return false;
});
$(canvas).on('touchend', function (e) {
if(leftMButtonDown) {
leftMButtonDown = false;
isSign = true;
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas">Canvas is not supported</canvas>
I need 3 canvas boxes, that can be signed parallel to each other. Is it possible to give me a hint or a tutorial or something that will make me understand what I need to change?
Not quite sure if this is what you mean (maybe three independent sign-in boxes?).
Use 3 HTML5 <canvas> elements, and initialize them. Then use the drawImage() function to copy the first canvas image onto the canvas context of the other two.
var isSign = false;
var leftMButtonDown = false;
jQuery(function(){
//Initialize sign pad
init_Sign_Canvas();
});
function fun_submit() {
if(isSign) {
var canvas = $("#canvas").get(0);
var imgData = canvas.toDataURL();
jQuery('#page').find('p').remove();
jQuery('#page').find('img').remove();
jQuery('#page').append(jQuery('<p>Your Sign:</p>'));
jQuery('#page').append($('<img/>').attr('src',imgData));
closePopUp();
} else {
alert('Please sign');
}
}
function closePopUp() {
jQuery('#divPopUpSignContract').popup('close');
jQuery('#divPopUpSignContract').popup('close');
}
function init_Sign_Canvas() {
isSign = false;
leftMButtonDown = false;
//Set Canvas width
var sizedWindowWidth = $(window).width();
if(sizedWindowWidth > 700)
sizedWindowWidth = $(window).width() / 2;
else if(sizedWindowWidth > 400)
sizedWindowWidth = sizedWindowWidth - 100;
else
sizedWindowWidth = sizedWindowWidth - 50;
$("#canvas").width(200);
$("#canvas").height(50);
$("#canvas").css("border","1px solid #000");
$("#canvas2").width(200);
$("#canvas2").height(50);
$("#canvas2").css("border","1px solid #000");
$("#canvas3").width(200);
$("#canvas3").height(50);
$("#canvas3").css("border","1px solid #000");
var canvas = $("#canvas").get(0);
var canvas2 = $("#canvas2").get(0);
var canvas3 = $("#canvas3").get(0);
canvasContext = canvas.getContext('2d');
canvas2ctx = canvas2.getContext('2d');
canvas3ctx = canvas3.getContext('2d');
if(canvasContext)
{
canvasContext.canvas.width = 200;
canvasContext.canvas.height = 50;
canvas2ctx.canvas.width = 200;
canvas2ctx.canvas.height = 50;
canvas3ctx.canvas.width = 200;
canvas3ctx.canvas.height = 50;
canvasContext.fillStyle = "#fff";
canvasContext.fillRect(0,0,sizedWindowWidth,200);
canvasContext.moveTo(50,150);
canvasContext.lineTo(sizedWindowWidth-50,150);
canvasContext.stroke();
canvasContext.fillStyle = "#000";
canvasContext.font="20px Arial";
canvasContext.fillText("x",40,155);
}
// Bind Mouse events
$(canvas).on('mousedown', function (e) {
if(e.which === 1) {
leftMButtonDown = true;
canvasContext.fillStyle = "#000";
var x = e.pageX - $(e.target).offset().left;
var y = e.pageY - $(e.target).offset().top;
canvasContext.moveTo(x, y);
}
e.preventDefault();
return false;
});
$(canvas).on('mouseup', function (e) {
if(leftMButtonDown && e.which === 1) {
leftMButtonDown = false;
isSign = true;
canvas2ctx.drawImage(canvas,0,0);
canvas3ctx.drawImage(canvas,0,0);
}
e.preventDefault();
return false;
});
// draw a line from the last point to this one
$(canvas).on('mousemove', function (e) {
if(leftMButtonDown == true) {
canvasContext.fillStyle = "#000";
var x = e.pageX - $(e.target).offset().left;
var y = e.pageY - $(e.target).offset().top;
canvasContext.lineTo(x,y);
canvasContext.stroke();
}
e.preventDefault();
return false;
});
//bind touch events
$(canvas).on('touchstart', function (e) {
leftMButtonDown = true;
canvasContext.fillStyle = "#000";
var t = e.originalEvent.touches[0];
var x = t.pageX - $(e.target).offset().left;
var y = t.pageY - $(e.target).offset().top;
canvasContext.moveTo(x, y);
e.preventDefault();
return false;
});
$(canvas).on('touchmove', function (e) {
canvasContext.fillStyle = "#000";
var t = e.originalEvent.touches[0];
var x = t.pageX - $(e.target).offset().left;
var y = t.pageY - $(e.target).offset().top;
canvasContext.lineTo(x,y);
canvasContext.stroke();
e.preventDefault();
return false;
});
$(canvas).on('touchend', function (e) {
if(leftMButtonDown) {
leftMButtonDown = false;
isSign = true;
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas">Canvas is not supported</canvas>
<canvas id="canvas2">Canvas is not supported</canvas>
<canvas id="canvas3">Canvas is not supported</canvas>

How to draw a box at a set coordination

I want to have a function that draws a box in the coordinates x and y.
I can't find a guide that doesn't answer more/less than what i want.
Thank's in advance.
I wrote this script some time ago so there may be ways to update it, but the idea is to get the position of the cursor onmousedown and attach an onmousemove listener. Each time you move the mouse you adjust th size of the box based on the position. Then on mouseup you remove the onmousemove listener.
https://jsfiddle.net/47nmp90w/
dragBox = (function() {
var _curX;
var _curY;
var _workingEl;
var _docEl = document.documentElement;
if (_docEl.scrollTop === 0) {
var testDocEl = _docEl.scrollTop;
_docEl.scrollTop++;
_docEl = testDocEl+1 === _docEl.scrollTop-- ? _docEl : document.body;
}
return {
drag: function(e) {
var evt = e ? e : window.event;
_width = Math.abs(_curX - evt.clientX);
_height = Math.abs(_curY - evt.clientY);
if (evt.shiftKey) {
var minDimension = Math.min(_width, _height) + 'px';
_workingEl.style.width = minDimension;
_workingEl.style.height = minDimension;
} else {
_workingEl.style.width = _width + 'px';
_workingEl.style.height = _height + 'px';
}
_workingEl.style.left = Math.min(_curX, evt.clientX) + _docEl.scrollLeft + 'px';
_workingEl.style.top = Math.min(_curY, evt.clientY) + _docEl.scrollTop + 'px';
},
draw: function(e) {
var evt = e ? e : window.event;
if (evt.which === 1) {
_curX = evt.clientX;
_curY = evt.clientY;
_workingEl = document.createElement('div');
_workingEl.className = 'drawing';
document.body.appendChild(_workingEl);
window.onmousemove = dragBox.drag;
window.onmouseup = function() {
window.onmousemove = null;
_workingEl.className = 'done';
_workingEl = false;
}
}
}
};
})();
window.onmousedown = dragBox.draw;
Edit
Here is how you would create a box with a set a data. You just set height and width styles, then give it a left position equal to your x coordinate and a top position of your y coordinate.
https://jsfiddle.net/RDay/47nmp90w/4/
var createButton = document.getElementById('create');
var xPosInput = document.getElementById('x-pos');
var yPosInput = document.getElementById('y-pos');
var widthInput = document.getElementById('width');
var heightInput = document.getElementById('height');
var target = document.getElementById('target');
createButton.onclick = function() {
var xPos = xPosInput.value;
var yPos = yPosInput.value;
var width = widthInput.value;
var height = heightInput.value;
var box = document.createElement('div');
box.className = 'box';
box.style.left = xPos + 'px';
box.style.top = yPos + 'px';
box.style.width = width + 'px';
box.style.height = height + 'px';
box.style.left = xPos + 'px';
target.appendChild(box);
};

how to draw a triangle with mouse like in Microsoft windows paint app?

I have written the code but it's for drawing a rectangle, i need to draw triangle shape by dragging the mouse while onClick, like in windows paint App. how to drag the mouse so that triangle forms automatically?
initDraw(document.getElementById('canvas'));
function initDraw(canvas) {
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
function setMousePosition(e) { // setting the postion for mouse
var ev = e || window.event;
if (ev.pageX) {
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) {
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.z = ev.clientZ + document.body.scrollLeft;
} };
var element = null;
canvas.onmousemove = function (e) {// on move
setMousePosition(e);
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}}};
canvas.onclick = function (e) {// on click function
if (element !== null) {
element = null;
canvas.style.cursor = "default";
console.log("finsihed.");
} else {
console.log("begun.");
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'triangle'
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element)
canvas.style.cursor = "crosshair";
}}}

How can I copy the contents of clipped HTML canvas region?

I am trying to copy the contents of a clipped canvas region. I am using a onmousemove listener to capture a given region, and would like to copy its contents upon the occurence of an onclick event:
var started = false;
editor_canvas.onmousemove = function (e) {
e = e || window.event;
var x = event.pageX;
var y = event.pageY;
if (!started) {
editor_context.beginPath();
editor_context.moveTo(x, y);
started = true;
return;
}
var rect = editor_canvas.getBoundingClientRect();
x = x - rect.left;
y = y - rect.top;
editor_context.lineWidth = 5;
editor_context.strokeStyle = 'red';
editor_context.lineTo(x, y);
editor_context.stroke();
};
editor_canvas.onclick = function(e) {
editor_context.clip();
}
JSFiddle here: http://jsfiddle.net/0nn78uxr/

Window.Onload function not firing in IE 10

I am trying to create a zooming and panning app to work across all browsers. It works in all other browsers, but in IE 10- just doesn't load the image, but does redraw it when I click on canvas to zoom in. Here's the window.onload part of the code:
window.onload = function(){
var ctx = canvas.getContext('2d');
trackTransforms(ctx);
function redraw(){
ctx.save();
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.restore();
ctx.drawImage(map,0,0, canvas.width, canvas.height);
}
redraw();
var lastX=canvas.width/2, lastY=canvas.height/2;
var dragStart,dragged;
canvas.addEventListener('mousedown',function(evt){
document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = 'none';
lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
dragStart = ctx.transformedPoint(lastX,lastY);
dragged = false;
},false);
canvas.addEventListener('mousemove',function(evt){
lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft);
lastY = evt.offsetY || (evt.pageY - canvas.offsetTop);
dragged = true;
if (dragStart){
var pt = ctx.transformedPoint(lastX,lastY);
ctx.translate(pt.x-dragStart.x,pt.y-dragStart.y);
redraw();
}
},false);
canvas.addEventListener('mouseup',function(evt){
dragStart = null;
if (!dragged) zoom(evt.shiftKey ? -1 : 1 );
},false);
var scaleFactor = 1.1;
var zoom = function(clicks){
var pt = ctx.transformedPoint(lastX,lastY);
ctx.translate(pt.x,pt.y);
var factor = Math.pow(scaleFactor,clicks);
ctx.scale(factor,factor);
ctx.translate(-pt.x,-pt.y);
redraw();
}
var handleScroll = function(evt){
var delta = evt.wheelDelta ? evt.wheelDelta/40 : evt.detail ? -evt.detail : 0;
if (delta) zoom(delta);
return evt.preventDefault() && false;
};
canvas.addEventListener('DOMMouseScroll',handleScroll,false);
canvas.addEventListener('mousewheel',handleScroll,false);
};
map.src = 'http://www.theodora.com/maps/new9/time_zones_4.jpg';

Categories