making box edge follow mouse pointer in javascript - javascript

I can't figure out why this doesn't work. What I have here is my own black canvas made from a DIV. In that canvas, I want the user to define the first point which I'm successful at, but after clicking the first point, when the mouse moves, the box must size properly and follow the mouse, much like drawing a rectangular box in a paint program. This is where I have difficulty.
Is there a way I can solve this such that it works at minimum and without using Jquery? all the better if I can get a solution for Internet Explorer 7 (or 8 at least).
<div ID="CANVAS" style="background:#000;width:600px;height:400px"></div>
<script>
var startx=-1,starty=-1,points=0,box;
var canvas=document.getElementById('CANVAS');
canvas.onclick=dopoint;
canvas.onmousemove=sizebox;
function dopoint(e){
if (points==0){
var area=canvas.getBoundingClientRect();
box=document.createElement('DIV');
box.style.position='relative';
box.style.border='2px solid yellow';
canvas.appendChild(box);
startx=e.clientX-area.left;
starty=e.clientY-area.top;
box.style.left=startx+'px';
box.style.top=starty+'px';
box.style.width='10px';
box.style.height='10px';
}
points=1-points;
}
function sizebox(e){
if (points==1){
var x=e.clientY,y=e.clientY; //here I'm thinking subtract old point from new point to get distance (for width and height)
if (x>startx){
box.style.left=startx+'px';
box.style.width=(x-startx)+'px';
}else{
box.style.left=x+'px';
box.style.width=(startx-x)+'px';
}
if (y>starty){
box.style.top=starty+'px';
box.style.height=(y-starty)+'px';
}else{
box.style.top=y+'px';
box.style.height=(starty-y)+'px';
}
}
}
</script>

Your code was almost good, except few small things. I have corrected it and wrote some comments on the lines that I've changed.
https://jsfiddle.net/1brz1gpL/3/
var startx=-1,starty=-1,points=0,box;
var canvas=document.getElementById('CANVAS');
canvas.onclick=dopoint;
canvas.onmousemove=sizebox;
function dopoint(e){
if (points==0){
var area=canvas.getBoundingClientRect();
box=document.createElement('DIV');
box.style.position='absolute'; // here was relative and changed to absolute
box.style.border='2px solid yellow';
canvas.appendChild(box);
startx=e.clientX; // removed -area.left
starty=e.clientY; // removed -area.right
box.style.left=startx+'px';
box.style.top=starty+'px';
box.style.width='0px'; // updated to 0px instead of 10 so it won't "jump" after you move the mouse with less then 10px
box.style.height='0px'; // same
}
points=1-points;
}
function sizebox(e){
if (points==1){
var x=e.clientX,y=e.clientY; // here was x = e.clientY and changed to x = clientX
if (x>=startx){
box.style.left=startx+'px';
box.style.width=(x-startx)+'px'; // here it was x+startx and changed to x-startx
}else{
box.style.left=x+'px';
box.style.width=(startx-x)+'px';
}
if (y>starty){
box.style.top=starty+'px';
box.style.height=(y-starty)+'px';
}else{
box.style.top=y+'px';
box.style.height=(starty-y)+'px';
}
}
}

Related

Unexpected border pattern in a grid with rectangles in p5.js

I am trying to generate a square grid like pattern in p5js that covers as much of the browser window as possible.I am using p5js in instance mode as I using this with react and I am using chrome in Win10.
Here is my code:-
var size = 15;
var height = window.innerHeight;
var width = window.innerWidth;
Sketch = (p) => {
p.setup = () => {
p.createCanvas(width,height)
p.frameRate(60);
p.noLoop();
}
p.draw = () => {
p.background(250);
p.stroke(0);
p.noFill();
for(let i =0;i*size +size <width;i++) {
for(let j=0;j*size +size<height;j++) {
p.rect(i*size,j*size,size,size);
}
}
}
p.mouseDragged = (e) => {
p.stroke(0);
let x = Math.floor(e.clientY/size);
let y = Math.floor(e.clientX/size);
p.fill(220);
p.rect(y*size,x*size,size,size);
}
}
I call p.noLoop() so it doesnt refreshes everytime and I also have a button that calls p.redraw() to change everything to default. Here is the grid and behaviour I get:
The borders of grids are of varying sizes, first they decrease then increase then decrease and so on. Also, the area around which I drag my mouse has even more weird borders(This gets resolved when I click somewhere else so is this a GPU Aliasing rendering issue?). How do I create grid with same borders throughout my screen?
Edit: When I render even a single box, it has issues. The left and upper border are fine. However the right and down borders have an extra pixel of grayish borders which seems to be the problem. How do I fix this?
Also, How does strokeWeight and rect work in p5js? If I do strokeWeight(10) and rect(3,2,50,50), does that create a 50 by 50 rectangle with 10 pixels borders all around or the borders are included in the rectangle size?

Shouldn't this code make the whole picture black?

In p5.js, I am trying to process each pixel of an image for a personal project so I thought I would start out slow and just try to make each pixel black. For some reason the screen is just staying white and I have no idea why the pixels aren't being updated. Here's the code:
var Canvas;
var srcImg;
var defaultImg = "http://i.imgur.com/ARg0OOy.jpg";
function preload() {
srcImg = loadImage(defaultImg);
}
function setup () {
createCanvas(srcImg.width,srcImg.height);
noLoop();
}
function draw() {
srcImg.loadPixels();
for (var x = 0; x < srcImg.width; x++) {
for (var y = 0; y < srcImg.height; y++) {
var loc = x + y*srcImg.width;
srcImg.pixels[loc] = color(224,29,29);
}
}
console.log(loc);
console.log(srcImg.width);
console.log(srcImg.height);
console.log(srcImg.width * srcImg.height);
srcImg.updatePixels();
//image(srcImg, 0,0,srcImg.width, srcImg.height);
}
Also, if I uncomment the last line, I see the original picture and it is cut off at the top (and it hasn't turned every pixel black). You can see for yourself here. Any thoughts on why this is happening?
Edit: I tried even doing one row of pixels to be a vibrant red color and the reason I'm getting a white screen is because no matter what color I set the pixels to, they become white... Also, when I tried making the whole row this red color, it stopped at about 1/4 the way through as shown here (and is still white). I don't know why this is happening.
You're making all of the pixels black, but then you're drawing srcImage on top of those black pixels. So all you see is srcImage.
Try commenting out the image(srcImg, 0,0,srcImg.width, srcImg.height); line to see the black pixels.

Paper.js Subraster Selecting Wrong Area

I'm working in a Paper.js project where we're essentially doing image editing. There is one large Raster. I'm attempting to use the getSubRaster method to copy a section of the image (raster) that the user can then move around.
After the raster to edit is loaded, selectArea is called to register these listeners:
var selectArea = function() {
if(paper.project != null) {
var startDragPoint;
paper.project.layers[0].on('mousedown', function(event) { // TODO should be layer 0 in long run? // Capture start of drag selection
if(event.event.ctrlKey && event.event.altKey) {
startDragPoint = new paper.Point(event.point.x + imageWidth/2, (event.point.y + imageHeight/2));
//topLeftPointOfSelectionRectangleCanvasCoordinates = new paper.Point(event.point.x, event.point.y);
}
});
paper.project.layers[0].on('mouseup', function(event) { // TODO should be layer 0 in long run? // Capture end of drag selection
if(event.event.ctrlKey && event.event.altKey) {
var endDragPoint = new paper.Point(event.point.x + imageWidth/2, event.point.y + imageHeight/2);
// Don't know which corner user started dragging from, aggregate the data we have into the leftmost and topmost points for constructing a rectangle
var leftmostX;
if(startDragPoint.x < endDragPoint.x) {
leftmostX = startDragPoint.x;
} else {
leftmostX = endDragPoint.x;
}
var width = Math.abs(startDragPoint.x - endDragPoint.x);
var topmostY;
if(startDragPoint.y < endDragPoint.y) {
topmostY = startDragPoint.y;
} else {
topmostY = endDragPoint.y;
}
var height = Math.abs(startDragPoint.y - endDragPoint.y);
var boundingRectangle = new paper.Rectangle(leftmostX, topmostY, width, height);
console.log(boundingRectangle);
console.log(paper.view.center);
var selectedArea = raster.getSubRaster(boundingRectangle);
var selectedAreaAsDataUrl = selectedArea.toDataURL();
var subImage = new Image(width, height);
subImage.src = selectedAreaAsDataUrl;
subImage.onload = function(event) {
var subRaster = new paper.Raster(subImage);
// Make movable
subRaster.onMouseEnter = movableEvents.showSelected;
subRaster.onMouseDrag = movableEvents.dragItem;
subRaster.onMouseLeave = movableEvents.hideSelected;
};
}
});
}
};
The methods are triggered at the right time and the selection box seems to be the right size. It does indeed render a new raster for me that I can move around, but the contents of the raster are not what I selected. They are close to what I selected but not what I selected. Selecting different areas does not seem to yield different results. The content of the generated subraster always seems to be down and to the right of the actual selection.
Note that as I build the points for the bounding selection rectangle I do some translations. This is because of differences in coordinate systems. The coordinate system where I've drawn the rectangle selection has (0,0) in the center of the image and x increases rightward and y increases downward. But for getSubRaster, we are required to provide the pixel coordinates, per the documentation, which start at (0,0) at the top left of the image and increase going rightward and downward. Consequently, as I build the points, I translate the points to the raster/pixel coordinates by adding imageWidth/2 and imageHeight/2`.
So why does this code select the wrong area? Thanks in advance.
EDIT:
Unfortunately I can't share the image I'm working with because it is sensitive company data. But here is some metadata:
Image Width: 4250 pixels
Image Height: 5500 pixels
Canvas Width: 591 pixels
Canvas Height: 766 pixels
My canvas size varies by the size of the browser window, but those are the parameters I've been testing in. I don't think the canvas dimensions are particularly relevant because I'm doing everything in terms of image pixels. When I capture the event.point.x and event.point.y to the best of my knowledge these are image scaled coordinates, but from a different origin - the center rather than the top left. Unfortunately I can't find any documentation on this. Observe how the coordinates work in this sketch.
I've also been working on a sketch to illustrate the problem of this question. To use it, hold Ctrl + Alt and drag a box on the image. This should trigger some logging data and attempt to get a subraster, but I get an operation insecure error, which I think is because of security settings in the image request header. Using the base 64 string instead of the URL doesn't give the security error, but doesn't do anything. Using that string in the sketch produces a super long URL I can't paste here. But to get that you can download the image (or any image) and convert it here, and put that as the img.src.
The problem is that the mouse events all return points relative to 0, 0 of the canvas. And getSubRaster expects the coordinates to be relative to the 0, 0 of the raster item it is extracting from.
The adjustment needs to be eventpoint - raster.bounds.topLeft. It doesn't really have anything to do with the image width or height. You want to adjust the event points so they are relative to 0, 0 of the raster, and 0, 0 is raster.bounds.topLeft.
When you adjust the event points by 1/2 the image size that causes event points to be offset incorrectly. For the Mona Lisa example, the raster size (image size) is w: 320, h: 491; divided by two they are w: 160, h: 245.5. But bounds.topLeft of the image (when I ran my sketch) was x: 252.5, y: 155.5.
Here's a sketch that shows it working. I've added a little red square highlighting the selected area just to make it easier to compare when it's done. I also didn't include the toDataURL logic as that creates the security issues you mentioned.
Here you go: Sketch
Here's code I put into an HTML file; I noticed that the sketch I put together links to a previous version of the code that doesn't completely work.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Rasters</title>
<script src="./vendor/jquery-2.1.3.js"></script>
<script src="./vendor/paper-0.9.25.js"></script>
</head>
<body>
<main>
<h3>Raster Bug</h3>
<div>
<canvas id="canvas"></canvas>
</div>
<div id="position">
</div>
</main>
<script>
// initialization code
$(function() {
// setup paper
$("#canvas").attr({width: 600, height: 600});
var canvas = document.getElementById("canvas");
paper.setup(canvas);
// show a border to make range of canvas clear
var border = new paper.Path.Rectangle({
rectangle: {point: [0, 0], size: paper.view.size},
strokeColor: 'black',
strokeWidth: 2
});
var tool = new paper.Tool();
// setup mouse position tracking
tool.on('mousemove', function(e) {
$("#position").text("mouse: " + e.point);
});
// load the image from a dataURL to avoid CORS issues
var raster = new paper.Raster(dataURL);
raster.position = paper.view.center;
var lt = raster.bounds.topLeft;
var startDrag, endDrag;
console.log('rb', raster.bounds);
console.log('lt', lt);
// setup mouse handling
tool.on('mousedown', function(e) {
startDrag = new paper.Point(e.point);
console.log('sd', startDrag);
});
tool.on('mousedrag', function(e) {
var show = new paper.Path.Rectangle({
from: startDrag,
to: e.point,
strokeColor: 'red',
strokeWidth: 1
});
show.removeOn({
drag: true,
up: true
});
});
tool.on('mouseup', function(e) {
endDrag = new paper.Point(e.point);
console.log('ed', endDrag);
var bounds = new paper.Rectangle({
from: startDrag.subtract(lt),
to: endDrag.subtract(lt)
});
console.log('bounds', bounds);
var sub = raster.getSubRaster(bounds);
sub.bringToFront();
var subData = sub.toDataURL();
sub.remove();
var subRaster = new paper.Raster(subData);
subRaster.position = paper.view.center;
});
});
var dataURL = ; // insert data or real URL here
</script>
</body>
</html>

Constrain jquery draggable to stay only on the path of a circle

So Im trying to make something where the user is able to drag planets along their orbits and it will continuously update the other planets. Ideally I would like this to work with ellipses too.
So far I can drag an image node with jquery and check/change the coordinates, but i cannot update the position reliably while the user is dragging the object. I know there is an axis and a rectangle containment for draggable but this doesn't really help me.
I have a site for calculating planetary orbits http://www.stjarnhimlen.se/comp/ppcomp.html and a formula i think should help me if i can figure out how to constrain the draggable object with coordinate checks Calculating point on a circle's circumference from angle in C#?
But it seems like there should be an easier way to have a user drag a sphere along a circular track while it updates coords for other spheres
here's what i have so far. It's not much
http://jsfiddle.net/b3247uc2/2/
Html
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
Js
var $newPosX = 100,
$newPosY = 100;
//create image node
var x = document.createElement("IMG");
x.src = "http://upload.wikimedia.org/wikipedia/commons/a/a4/Sol_de_Mayo_Bandera_Argentina.png";
x.width = 100;
x.height = 100;
x.id = "sun";
x.hspace = 100;
x.vspace = 100;
document.body.appendChild(x);
//coords
var text = document.createTextNode($newPosX + " " + $newPosY);
document.body.appendChild(text);
//make sun draggable and update coords
$("#sun").draggable({
drag: function (event, ui) {
$newPosX = $(this).offset().left;
$newPosY = $(this).offset().top;
}
});
//0 millisecond update for displayed coords
setInterval(check, 0);
function check() {
//tries to constrain movement, doesn't work well
/*
if ($newPosX > 300) {
$("#sun").offset({
left: 200
});
}
*/
text.nodeValue = ($newPosX + " " + $newPosY);
}
Edit:
I found this and am trying to modify it to suit my purposes but have so far not had luck.
http://jsfiddle.net/7Asn6/
Ok so i got it to drag
http://jsfiddle.net/7Asn6/103/
This is pretty close to what I want but can be moved without being clicked on directly
http://jsfiddle.net/7Asn6/104/
Ok final edit on this question. This one seems to work well and have fixed my problems. I would still very much like to hear peoples implementation ideas or ideas to make it work smoother.
http://jsfiddle.net/7Asn6/106/

HTML5 photoshop like polygonal lasso selection

Im looking to build a tool to cut out a portion of a photo by letting the user create a closed shape. The user should be able to start drawing lines. From point a to point b, to c, e, d, e, f .... to eventually point a again to close the shape.
I want to use the HTML5 canvas for this. I think this could be a good fit and I'm thinking about using something like flashcanvas as fallback for IE/older browsers?
Is there any tutorial/open source application that I could use to build this sort of thing?
This is the first time I'm going to build an application using HTML5 canvas so are there any pitfalls I should worry about?
I think this is advanced usage of canvas. You have to know the basics, how to draw, how to use layers, how to manipulate pixels. Just ask google for tutorials.
Assuming you know about the previous, I'll give it a try. I've never done that before but I have an idea :
You need 3 canvas :
the one containing your picture (size of your picture)
a layer where the user draw the selection shape (size of your picture, on top of the first canvas)
a result canvas, will contain your cropped picture (same size, this one doesn't need to be displayed)
When the user click on your picture : actually, he clicks on the layer, the layer is cleared and a new line begins.
When he clicks on it another time, the previous started line is drawn and another one begins, etc... You keep doing this until you click on a non-blank pixel (which means you close the shape).
If you want the user to preview the lines, you need another canvas ( explained here http://dev.opera.com/articles/view/html5-canvas-painting/#line )
When the shape is closed, the user has to click inside or outside the shape to determine which part he wants to select. You fill that part with a semi-transparent gray for example ( flood fill explained here http://www.williammalone.com/articles/html5-canvas-javascript-paint-bucket-tool/ )
Now the layer canvas contains a colored shape corresponding to the user selection.
Get the pixel data from your layer and read through the array, every time you find a non-blank pixel at index i, you copy this pixel from your main canvas to the result canvas :
/* First, get pixel data from your 3 canvas into
* layerPixData, resultPixData, picturePixData
*/
// read the entire pixel array
for (var i = 0 ; i < layerPixData.length ; i+=4 ) {
//if the pixel is not blank, ie. it is part of the selected shape
if ( layerPixData[i] != 255 || layerPixData[i+1] != 255 || layerPixData[i+2] != 255 ) {
// copy the data of the picture to the result
resultPixData[i] = picturePixData[i]; //red
resultPixData[i+1] = picturePixData[i+1]; //green
resultPixData[i+2] = picturePixData[i+2]; //blue
resultPixData[i+3] = picturePixData[i+3]; //alpha
// here you can put the pixels of your picture to white if you want
}
}
If you don't know how pixel manipulation works, read this https://developer.mozilla.org/En/HTML/Canvas/Pixel_manipulation_with_canvas
Then, use putImageData to draw the pixels to your result canvas. Job done !
If you want to move lines of your selection, way to go : http://simonsarris.com/blog/225-canvas-selecting-resizing-shape
Here is how you should do that:
The code at the following adds a canvas on top of your page and then by clicking and dragging on that the selection areas would be highlighted. What you need to do after that is to make a screenshot from the underlying page and also a mask layer out of the created image in your canvas and apply that to the screenshot, just like how it is shown in one other answers.
/* sample css code for the canvas
#overlay-canvas {
position: absolute;
top: 0;
left: 0;
background-color: transparent;
opacity: 0.4;
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
}
*/
function getHighIndex(selector) {
if (!selector) { selector = "*" };
var elements = document.querySelectorAll(selector) ||
oXmlDom.documentElement.selectNodes(selector);
var ret = 0;
for (var i = 0; i < elements.length; ++i) {
if (deepCss(elements[i],"position") === "static")
continue;
var temp = deepCss(elements[i], "z-index");
if (temp != "auto")
temp = parseInt(temp, 10) || 0;
else
continue;
if (temp > ret)
ret = temp;
}
return ret;
}
maxZIndex = getHighIndex();
$.fn.extend({
lasso: function () {
return this
.mousedown(function (e) {
// left mouse down switches on "capturing mode"
if (e.which === 1 && !$(this).is(".lassoRunning")) {
var point = [e.offsetX, e.offsetY];
$(this).addClass("lassoRunning");
$(this).data("lassoPoints", [point]);
$(this).trigger("lassoStart", [point]);
}
})
.mouseup(function (e) {
// left mouse up ends "capturing mode" + triggers "Done" event
if (e.which === 1 && $(this).is(".lassoRunning")) {
$(this).removeClass("lassoRunning");
$(this).trigger("lassoDone", [$(this).data("lassoPoints")]);
}
})
.mousemove(function (e) {
// mouse move captures co-ordinates + triggers "Point" event
if ($(this).is(".lassoRunning")) {
var point = [e.offsetX, e.offsetY];
$(this).data("lassoPoints").push(point);
$(this).trigger("lassoPoint", [point]);
}
});
}
});
function onLassoSelect() {
// creating canvas for lasso selection
var _canvas = document.createElement('canvas');
_canvas.setAttribute("id", "overlay-canvas");
_canvas.style.zIndex = ++maxZIndex;
_canvas.width = document.width
_canvas.height = document.height
document.body.appendChild(_canvas);
ctx = _canvas.getContext('2d'),
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
$(_canvas)
.lasso()
.on("lassoStart", function(e, lassoPoint) {
console.log('lasso start');
var pos = lassoPoint;
ctx.beginPath();
ctx.moveTo(pos[0], pos[1]);
console.log(pos);
})
.on("lassoDone", function(e, lassoPoints) {
console.log('lasso done');
var pos = lassoPoints[0];
ctx.lineTo(pos[0], pos[1]);
ctx.fill();
console.log(pos);
})
.bind("lassoPoint", function(e, lassoPoint) {
var pos = lassoPoint;
ctx.lineTo(pos[0], pos[1]);
ctx.fill();
console.log(pos);
});
}

Categories

Resources