How to draw shape in div - javascript

I am trying to draw shape in div element. The code below draws a shape in correct starting point if not transform scale. But if transform scale, the line is not in the correct position when drawing the shape. How to fix the code below if the div is transform scale in (0.7, 0.7)? Thank you in advance.
$(function() {
var $container = $('#container');
var $selection = $('<div>').addClass('selection-box');
$container.on('mousedown', function(e) {
var click_y = e.pageY,
click_x = e.pageX;
$selection.css({
'top': click_y,
'left': click_x,
'width': 0,
'height': 0
});
$selection.appendTo($container);
$container.on('mousemove', function(e) {
var move_x = e.pageX,
move_y = e.pageY,
width = Math.abs(move_x - click_x),
height = Math.abs(move_y - click_y),
new_x, new_y;
new_x = (move_x < click_x) ? (click_x - width) : click_x;
new_y = (move_y < click_y) ? (click_y - height) : click_y;
$selection.css({
'width': width,
'height': height,
'top': new_y,
'left': new_x
});
}).on('mouseup', function(e) {
$container.off('mousemove');
$selection.remove();
});
});
});

Related

Send coordinates of dynamically drawn box through AJAX

I am taking an image, saving the first click coordinates, drawing a box based on these then saving the final coordinates. I tried to output the coordinates using console.log() and it tracks the right coordinates. The problem is that it does not POST it properly.
$(document).ready(function () {
var $selection = $('<div>').addClass('selection-box');
var firstClick = true;
$('#image')
.data("vals", {xstart: 0, ystart:0})
.on('dragstart', function(e) { event.preventDefault(); })
.mousedown(function(e) {
var xval = Number(e.pageX - $(this).offset().left);
var yval = Number(e.pageY - $(this).offset().top);
console.log(xval)
$("#image").data("vals").xstart = e.pageX - $(this).offset().left;
$("#image").data("vals").ystart = e.pageY - $(this).offset().top;
$selection.css({
'top': yval,
'left': xval,
'width': 0,
'height': 0
});
$selection.appendTo($('#image'));
$('#image').mousemove(function(e) {
var move_x = e.pageX - $(this).offset().left,
move_y = e.pageY - $(this).offset().top,
width = Math.abs(move_x - xval),
height = Math.abs(move_y - yval),
new_x, new_y;
console.log(xval)
new_x = (move_x < xval) ? (xval - width) : xval;
new_y = (move_y < yval) ? (yval - height) : yval;
$selection.css({
'width': width,
'height': height,
'top': new_y,
'left': new_x
});
}).mouseup(function(e) {
xend = Number(e.pageX - $(this).offset().left);
yend= Number(e.pageY - $(this).offset().top);
//console.log(xval, yval, xend, yend);
$.ajax({
url: '/view/getwords/',
type:"POST",
data: {
xval: xval.toString(),
yval: yval.toString(),
xend: xend.toString(),
yend: yend.toString(),
},
dataType: 'json',
success: function (data) {
console.log(xval, yval, xend, yend);
},
error:function(){
alert("Error");
}
});
$('#image').off('mousemove')
$selection.remove();
})
})
});
P.S. This is one of my first questions on StackOverflow so let me know as well if I can ask questions better.
Thank you!
Edit: Here is the snippet of the boxing code I used. http://jsbin.com/ireqix/226/edit?html,js,output
Essentially, I am just trying to POST the coordinates from the snippet above.

Created an image with selected area of a webpage using javascript

Need to create an image with the selected area, I can able to select an area of a page with a background image and got the page X and Y co-ordinates and length of the selected area. I need to create an image of the selected area, or capture the selected area and save as image. But when I try with draw image it throws common.js?ocauxu:1912 Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'selectElements # common.js?ocauxu:1912dispatch # jquery.min.js?v=1.8.2:2h # jquery.min.js?v=1.8.2:2, need a mechanism to create an image with the data I gave, below is the code I have which I tried in Drupal 7.
$(document).ready(function(){
$('body').append('<div class="ghost-select"><span></span></div><canvas id="myCanvas" width="220" height="277" style="border:1px solid #d3d3d3;">');
$(document).mousedown(function (e) {
$("#big-ghost").remove();
$(".ghost-select").addClass("ghost-active");
$(".ghost-select").css({
'left': e.pageX,
'top': e.pageY
});
initialW = e.pageX;
initialH = e.pageY;
$(document).bind("mouseup", selectElements);
$(document).bind("mousemove", openSelector);
});
});
function selectElements(e) {
$("#score>span").text('0');
$(document).unbind("mousemove", openSelector);
$(document).unbind("mouseup", selectElements);
//Tried to create an image but not working
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.drawImage(img, 0, 0);
canvas.toDataURL();
var img = document.getElementsByClassName("ghost-select");
var imgData = ctx.getImageData(0, 0, c.width, c.height);
$(".ghost-select").removeClass("ghost-active");
$(".ghost-select").width(0).height(0);
}
function openSelector(e) {
var w = Math.abs(initialW - e.pageX);
var h = Math.abs(initialH - e.pageY);
$(".ghost-select").css({
'width': w,
'height': h
});
if (e.pageX <= initialW && e.pageY >= initialH) {
$(".ghost-select").css({
'left': e.pageX
});
} else if (e.pageY <= initialH && e.pageX >= initialW) {
$(".ghost-select").css({
'top': e.pageY
});
} else if (e.pageY < initialH && e.pageX < initialW) {
$(".ghost-select").css({
'left': e.pageX,
"top": e.pageY
});
}
}

Use JQuery to fix element from bottom of window

I found plenty of examples of fixing an element's top relative to the window. How do I fix an element X pixels from the bottom of the window? Simply changing 'top' to 'bottom' does not work (for example,if the element's height is more than the window height)
From the top:
var pixels = 10;
var $elemPosition = $element.position();
var $elementH = $element.height();
var $windowH = $(window).height();
var $bottom = $element.offset().top + $element.height();
if ($(window).scrollTop() + pixels >= $elemPosition.top) {
$element.css({
'position': 'fixed',
'top': pixels + 'px'
});
} else {
$element.css({
'position': 'relative',
'top': '0px'
});
}
Solved it! Solution I came up with:
if (($windowH + $(window).scrollTop() - $bottom - pixels) >= 0) {
$element.css({
'position': 'fixed',
'top': ($windowH - $element.height() - pixels) + 'px',
'width': $eW + 'px',
'height': $eH + 'px'
});
} else {
$element.css({
'position': 'relative',
'top': '0px'
});
}
Use the CSS bottom property instead of the top property.
$element.css({
'position': 'fixed',
'bottom': pixels + 'px'
});
According to your comments and demand :
for example,if the element's height is more than the window height
You wants something like this ?
JS
$element = $("#element");
function setPosition(){
var pixels = 10;
var $elementH = $element.height();
var $windowH = $(window).height();
if ($windowH > $elementH) {
$element.css({
'position': 'fixed',
'bottom': pixels + 'px'
});
} else {
$element.css({
'position': 'relative',
'bottom': '0px'
});
}
}
$(function(){
setPosition();
$(window).scroll(function(){
setPosition();
});
});
If you try to change the height of the element to 700px for instance, you'll see he gets relative position.

Placing cursor in the center of a child div - mousemove event

I have div that can be placed anywhere inside another div. I am able to do this with jquery mousemove event. However it is not quite working. I am trying to get the mouse cursor to be in the center of the moving div. I set these css attributes inline with jquery 'top': relY + 30,'left': relX + 10 but no luck. As mention I am trying to get the cursor in the middle of the div. The user can only place the moving inside the parent div called middle-side empty. JSFIDDLE
I am trying to accomplish something similar to this: http://jsfiddle.net/Lqebpaov/
Jquery:
$('#button').click(function (e) {
$('<div />', {
class: 'draggable ui-widget-content',
text: $('textarea').val(),
appendTo: '.middle-side',
draggable: {
containment: 'parent'
}
}).addClass('placement');
$('.middle-side').parent().mousemove(function(e){
var offset = $(this).offset();
var relX = e.pageX - offset.left;
var relY = e.pageY - offset.top;
$('.placement').css({'top': relY + 30,'left': relX + 10, 'position': 'absolute'});
})
});
$('.middle-side').on('click', function(e){
var offset = $(this).offset();
var relX = e.pageX - offset.left;
var relY = e.pageY - offset.top;
$('.placement').css({'top': relY,'left': relX, 'position': 'absolute' });
$(this).off("mousemove").find('.placement').removeClass('placement')
});
HTML
<div>
<div class="middle-side empty"></div>
</div>
This was a fun question. I updated a lot of your Javascript, and set up my own JSFIDDLE.
With this setup you should be able to resize the boxes to any height/width combination and it will work as expected. You can check out the JSFIDDLE link, but here is the updated Javascript also:
$('#button').click(function (e) {
$('<div />', {
class: 'draggable ui-widget-content',
text: $('textarea').val(),
appendTo: '.middle-side',
draggable: {
containment: 'parent'
}
}).addClass('placement');
$('.middle-side').parent().mousemove(function(e){
var offset = $(this).offset(),
relX = e.pageX,
relY = e.pageY,
$dvPlacement = $('.placement'),
pWidth = $dvPlacement.outerWidth(),
pHeight = $dvPlacement.outerHeight(),
$dvOutBox = $('.middle-side'),
oWidth = $dvOutBox.outerWidth(),
oHeight = $dvOutBox.outerHeight(),
centerY = relY - pHeight / 2,
centerX = relX - pWidth / 2,
topBorder = $dvOutBox.offset().top,
bottomBorder = $dvOutBox.offset().top + oHeight,
leftBorder = $dvOutBox.offset().left,
rightBorder = $dvOutBox.offset().left + oWidth;
$dvPlacement.css({'top': centerY + pHeight > bottomBorder ? bottomBorder - pHeight :
centerY < topBorder ? topBorder :
centerY,
'left': centerX + pWidth > rightBorder ? rightBorder - pWidth :
centerX < leftBorder ? leftBorder :
centerX,
'position': 'absolute'
});
})
});
$('.middle-side').on('click', function(e){
$(this).off("mousemove").find('.placement').removeClass('placement')
});
Change the placement offset to
$('.placement').css({'top': relY + 30,'left': relX - 75 , 'position': 'absolute'});
Demo

jQuery drag and draw

I'm trying to build a jQuery plugin that allows you to drag and draw a rectangle (or a div with a border) but I'm not sure how to do it. I don't know of any that currently have this ability so I don't know where to look for an example of how to do this.
How can I implement drag and draw in jQuery?
The basics for something like this are quite simple, when you think about it:
Listen for mousedown events on some container (possible the entire document);
Place an absolutely positioned element at the position of the mouse, using the mouse coordinates from the event object (e.pageX and e.pageY);
Start listening to mousemove events to change the width and height object (based on the mouse coordinates);
Listen for the mouseup event to detach the mousemove event listener.
The aforementioned absolute placed element is, e.g., a <div> with a border and background: transparent.
Update: here is an example:
$(function() {
var $container = $('#container');
var $selection = $('<div>').addClass('selection-box');
$container.on('mousedown', function(e) {
var click_y = e.pageY;
var click_x = e.pageX;
$selection.css({
'top': click_y,
'left': click_x,
'width': 0,
'height': 0
});
$selection.appendTo($container);
$container.on('mousemove', function(e) {
var move_x = e.pageX,
move_y = e.pageY,
width = Math.abs(move_x - click_x),
height = Math.abs(move_y - click_y),
new_x, new_y;
new_x = (move_x < click_x) ? (click_x - width) : click_x;
new_y = (move_y < click_y) ? (click_y - height) : click_y;
$selection.css({
'width': width,
'height': height,
'top': new_y,
'left': new_x
});
}).on('mouseup', function(e) {
$container.off('mousemove');
$selection.remove();
});
});
});
Demo: http://jsbin.com/ireqix/226/
$("#YOUR_ELEMENT_ID").on("mousedown", function (e) {
var click_x = e.pageX;
var click_y = e.pageY;
/* Posição do objeto */
var x = parseFloat($(this).css("left").replace("px", "")),
y = parseFloat($(this).css("top").replace("px", ""));
/* Calcula distância no eixo x */
var distanc_x = Math.abs(x - click_x);
var distanc_y = Math.abs(y - click_y);
$("#YOUR_ELEMENT_ID")
.on("mousemove", function (e) {
var new_x = e.pageX - distanc_x;
var new_y = e.pageY - distanc_y;
$(this).css({
top: new_y,
left: new_x,
});
}).on("mouseup", function (e) {
$(this).off("mousemove");
});
});

Categories