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
});
}
}
Related
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();
});
});
});
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.
I have a selection on a canvas, that I can drag and resize when it´s there.
I also can make it visible when I drag on the empty canvas.
But how do I make it visible and instantly have the bottom-right corner "in my hand" (for resizing); i.e. can I pass the drag event from the canvas to a resize event on the selection?
Is there a way with jQuery or do I have to make my own?
<div id="canvas" style="position:relative;width:500px;height:500px"
draggable="true" onDragStart="initSelection(event)">
<div id="selection" style="border:1px dashed gray;position:absolute;display:none"></div>
</div>
$('#selection').draggable({containment:'parent'}).resizable({containment:'parent'});
function initSelection(e){
if ('none'==$('#selection').css('display'))
{
var q=$('#canvas').offset();
$('#selection')
.css('left', e.clientX-q.left)
.css('top', e.clientY-q.top)
.css('width',10).css('height',10)
.css('display','block')
;
}
}
I think I see what you're trying to do.
Testing here: jsfiddle.net/Twisty/vkLjn0gL
I think you need to take one route or the other, not both at once.
resize the div with CSS based on the mousedown / mouseup events and
mouse x and y.
make it resizable up front and enable/start the resize
event tied to the mousemove until done and then make it draggable
I got this far when you posted that you found an answer: https://jsfiddle.net/Twisty/vkLjn0gL/5/
$(function() {
$("#canvas").on("dragstart", initSelection);
$("#canvas").on("mousemove", resize);
$("#canvas").on("mouseup", function() {
allowResize = false;
});
var allowResize = false;
/*
$('#selection').draggable({
containment: 'parent'
}).resizable({
containment: 'parent'
});
*/
function initSelection(e) {
if ('none' == $('#selection').css('display')) {
var q = $('#canvas').offset();
$('#selection')
.css('left', e.clientX - q.left)
.css('top', e.clientY - q.top)
.css('width', '10px').css('height', '10px')
.css('display', 'block');
allowResize = true;
}
}
function resize(e) {
if (allowResize) {
//console.log("MouseMove: ", e);
var w = $("#selection").width(),
h = $("#selection").height(),
q = $("#canvas").offset(),
px = 0,
py = 0;
px = e.clientX - q.left;
py = e.clientY - q.top;
console.log("Width: ", (w + px), " Height: ", (h + py));
$("#selection").css({
width: (w + px) + "px",
height: (h + py) + "px"
});
}
}
});
Update 1
Few fixes to mouse tracking:
https://jsfiddle.net/Twisty/vkLjn0gL/6/
function resize(e) {
if (allowResize) {
//console.log("MouseMove: ", e);
$("#canRes").html(allowResize);
$("#cx").html(e.clientX - $("#canvas").offset().left);
$("#cy").html(e.clientY - $("#canvas").offset().top);
$("#ox").html($("#selection").width());
$("#oy").html($("#selection").height());
var w = $("#selection").width(),
h = $("#selection").height(),
q = $("#canvas").offset(),
o = $("#selection").position();
px = 0,
py = 0;
if (w > $("#canvas").width() + q.left) {
return false;
}
if (h > $("#canvas").height() + q.top) {
return false;
}
px = e.clientX - q.left - o.left;
py = e.clientY - q.top - o.top;
$("#selection").css({
width: px + "px",
height: py + "px"
});
}
}
Update 2
I think this will do all that you wanted if you're still looking: https://jsfiddle.net/Twisty/vkLjn0gL/7/
Updated to selection after mouseup
$("#canvas").on("mouseup", function() {
allowResize = false;
$("#canRes").html(allowResize);
$("#selection").draggable({
containment: 'parent'
})
.resizable({
containment: 'parent'
});
});
Update 3
Added the drag handle on initial sizing: https://jsfiddle.net/Twisty/vkLjn0gL/10/
I am developing an app with Cordova + Onsen Ui 2 + javascript, but I am getting problems to get the coordinates X and Y from javascript move events. I tried mousemove (it didn't fire) and drag (but I got undefined when I tried to get pageX or clientX from event object). I didn't find any example about drawing with canvas yet. Thanks you all in advance!
Javascript:
var canvasListener = function(){
canvas = document.getElementById("canvas");
canvas.addEventListener('mousedown', function(event){
var coordinates = painting(event);
});
canvas.addEventListener('drag', function(event){
var coordinates = painting(event);
});
canvas.addEventListener('mouseup', function(event){
var coordinates = painting(event);
});
}
function painting(event){
var x = event.clientX;
var y = event.clientY;
var touchX = x - signatureCanvas.offsetLeft;
var touchY = y - signatureCanvas.offsetTop;
var localCoordinates;
if(event.type == 'mouseup'){
localCoordinates = {
x: 0,
y: 0
};
}else{
localCoordinates = {
x: touchX,
y: touchY
};
}
return localCoordinates;
}
Html:
<canvas id="canvas"></canvas>
Try this code. On moving mouse over the canvas the current mouse(x,y) co-ordinates will be printed in screen. Hope this logic only you are looking for.
JsFiddle
HTML
<canvas width="300" height="225"></canvas>
<span class="first">Move the mouse over the div.</span>
<span></span>
JS
var canvas = $('canvas');
canvas.mousemove(function(e){
var pageCrds = '('+ e.pageX +', '+ e.pageY +')',
clientCrds = '('+ e.clientX +', '+ e.clientY +')';
$('span:first').text('(e.pageX, e.pageY) - '+ pageCrds);
$('span:last').text('(e.clientX, e.clientY) - '+ clientCrds);
});
Generally you'll want to use event.clientX, event.clientY, and the results of canvas.getBoundingClientRect();. Here's an example, using the MouseMove event:
can.addEventListener('mousemove', function(e) {
var canwidth = can.width;
var canheight = can.height;
var bbox = can.getBoundingClientRect();
var mx = e.clientX - bbox.left * (canwidth / bbox.width);
var my = e.clientY - bbox.top * (canheight / bbox.height);
// output it to see results:
ctx.fillRect(mx, my, 1, 1);
})
This works with all mouse/touch events on all platforms, and accommodates a lot of difficult CSS situations.
Live example: http://codepen.io/simonsarris/pen/NNVQpj?editors=1010
Try this..
var damagesCanvas = document.getElementById('damagesCanvas');
damagesCanvas.addEventListener('click', function (evt) {
var pos = getMousePos(damagesCanvas, evt);
}, false);
function getMousePos(damagesCanvas, evt) {
var rect = damagesCanvas.getBoundingClientRect();
return {
X: evt.clientX - rect.left,
Y: evt.clientY - rect.top
};
}
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");
});
});