Related
Using certain methods, I drew a 3D cube.
My task is to rotate it around the z axis. I also need to rotate the cube relative to the coordinates (0,0,0) (on my canvas, these will be the coordinates (150,150,0)). Now it rotates correctly, but only changes its angle relative to the 'top left corner of my canvas'.
I think the solution to my problem is as follows:
To rotate the cube relative to the given coordinates, the cube must first be translated to the negative coordinates of this point, and by changing the angle, it must be translated back, but only to the positive coordinates of this point.
In my case the pseudo code would be like this:
// if I want to flip the cube around the coordinates (150,150,0) (this is the center of my canvas), then I need to do the following
translate(-150,-150,0);
rotate();
translate(150,150,0);
In the commented parts of the code, I tried to do this, but when I translate the cube, it gets stuck somewhere in the corner and I don't know how to fix it.
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
function randomColor() {
return "rgb(" + randInt(0,255) + "," + randInt(0,255) + "," + randInt(0,255) + ")";
}
function ctg(x) {
return 1 / Math.tan(x);
}
function draw() {
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
let canvasWidth = 300;
canvas.width = canvas.height = canvasWidth;
function drawUW() {
context.lineWidth = 0.1;
context.beginPath();
context.moveTo(0,canvas.height/2);
context.lineTo(canvas.width,canvas.height/2);
context.moveTo(canvas.width/2,0);
context.lineTo(canvas.width/2,canvas.height);
context.stroke();
}
function updateCanvas() {
context.clearRect(0,0,canvas.width,canvas.height);
drawUW();
}
let x = 50, y = 50, z = 50;
let d = 100;
let x0 = canvas.width/2;
let y0 = canvas.height/2;
let x1 = x0+x;
let y1 = y0;
let x2 = x0;
let y2 = y0-y;
let x3 = x0+x;
let y3 = y0-y;
// x' = xd/(z+d)
// y' = yd/(z+d)
let x0p=x0*d/(z+d);
let y0p=y0*d/(z+d);
let x1p=x1*d/(z+d);
let y1p=y1*d/(z+d);
let x2p=x2*d/(z+d);
let y2p=y2*d/(z+d);
let x3p=x3*d/(z+d);
let y3p=y3*d/(z+d);
function getWalls() {
wall01 = [[x0,x2,x3,x1],[y0,y2,y3,y1]];
wall02 = [[x0p,x2p,x2,x0],[y0p,y2p,y2,y0]];
wall03 = [[x0p,x2p,x3p,x1p],[y0p,y2p,y3p,y1p]];
wall04 = [[x1p,x3p,x3,x1],[y1p,y3p,y3,y1]];
wall05 = [[x2,x2p,x3p,x3],[y2,y2p,y3p,y3]];
wall06 = [[x0,x0p,x1p,x1],[y0,y0p,y1p,y1]];
}
function drawWall(wall) {
context.fillStyle = randomColor();
context.strokeStyle = "black";
context.lineWidth = 0.5;
context.beginPath();
context.moveTo(wall[0][0],wall[1][0]);
context.lineTo(wall[0][1],wall[1][1]);
context.lineTo(wall[0][2],wall[1][2]);
context.lineTo(wall[0][3],wall[1][3]);
context.lineTo(wall[0][0],wall[1][0]);
context.fill();
context.stroke();
}
function rotatePoint(x,y,z,fi) {
fi*=Math.PI/180;
arr = [x,y,z,1];
newX = 0;
newY = 0;
newZ = 0;
tx = -150, ty = -150, tz = -150;
arrTranslate = [
[1,0,0,tx],
[0,1,0,ty],
[0,0,1,tz],
[0,0,0,1]
];
// z
arrRotate = [
[Math.cos(fi),-Math.sin(fi),0,0],
[Math.sin(fi),Math.cos(fi),0,0],
[0,0,1,0],
[0,0,0,1]
];
// translate
// for (let i = 0; i < arr.length; i++) {
// newX += arr[i] * arrTranslate[0][i];
// newY += arr[i] * arrTranslate[1][i];
// newZ += arr[i] * arrTranslate[2][i];
// }
//rotate
for (let i = 0; i < arr.length; i++) {
newX += arr[i] * arrRotate[0][i];
newY += arr[i] * arrRotate[1][i];
newZ += arr[i] * arrRotate[2][i];
}
tx = 150, ty = 150, tz = 150;
// translate
// for (let i = 0; i < arr.length; i++) {
// newX += arr[i] * arrTranslate[0][i];
// newY += arr[i] * arrTranslate[1][i];
// newZ += arr[i] * arrTranslate[2][i];
// }
x = newX;
y = newY;
z = newZ;
return [newX,newY,newZ];
}
function rotatePoints(fi) {
x0 = rotatePoint(x0,y0,z,fi)[0];
y0 = rotatePoint(x0,y0,z,fi)[1];
x1 = rotatePoint(x1,y1,z,fi)[0];
y1 = rotatePoint(x1,y1,z,fi)[1];
x2 = rotatePoint(x2,y2,z,fi)[0];
y2 = rotatePoint(x2,y2,z,fi)[1];
x3 = rotatePoint(x3,y3,z,fi)[0];
y3 = rotatePoint(x3,y3,z,fi)[1];
x0p = rotatePoint(x0p,y0p,z,fi)[0];
y0p = rotatePoint(x0p,y0p,z,fi)[1];
x1p = rotatePoint(x1p,y1p,z,fi)[0];
y1p = rotatePoint(x1p,y1p,z,fi)[1];
x2p = rotatePoint(x2p,y2p,z,fi)[0];
y2p = rotatePoint(x2p,y2p,z,fi)[1];
x3p = rotatePoint(x3p,y3p,z,fi)[0];
y3p = rotatePoint(x3p,y3p,z,fi)[1];
}
let inFi = document.getElementById("fi");
inFi.addEventListener("change", updateImage);
function updateImage() {
rotatePoints(inFi.value);
getWalls();
updateCanvas();
drawWall(wall06);
drawWall(wall04);
drawWall(wall03);
drawWall(wall02);
drawWall(wall05);
drawWall(wall01);
}
updateImage();
}
<body onload="draw();">
<canvas id="canvas"></canvas>
<div><input type="number" id="fi" value="0"></div>
</body>
I am trying to find an algorithm of how to draw a simple (no lines are allowed to intersect), irregular polygon.
The number of sides should be defined by the user, n>3.
Here is an intial code which only draws a complex polygon (lines intersect):
var ctx = document.getElementById('drawpolygon').getContext('2d');
var sides = 10;
ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.moveTo(0, 0);
for(var i=0;i<sides;i++)
{
var x = getRandomInt(0, 100);
var y = getRandomInt(0, 100);
ctx.lineTo(x, y);
}
ctx.closePath();
ctx.fill();
// https://stackoverflow.com/a/1527820/1066234
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
JSFiddle: https://jsfiddle.net/kai_noack/op2La1jy/6/
I do not have any idea how to determine the next point for the connecting line, so that it does not cut any other line.
Further, the last point must close the polygon.
Here is an example of how one of the resulting polygons could look like:
Edit: I thought today that one possible algorithm would be to arrange the polygon points regular (for instance as an rectangle) and then reposition them in x-y-directions to a random amount, while checking that the generated lines are not cut.
I ported this solution to Javascript 1 to 1. Code doesn't look optimal but produces random convex(but still irregular) polygon.
//shuffle array in place
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
/** Based on Sander Verdonschot java implementation **/
class Point {
constructor(x, y) {
this.x = x;
this.y = y
}
}
function generateRandomNumbersArray(len) {
const result = new Array(len);
for (let i = 0; i < len; ++i) {
result[i] = Math.random();
}
return result;
}
function generateRandomConvexPolygon(vertexNumber) {
const xPool = generateRandomNumbersArray(vertexNumber);
const yPool = generateRandomNumbersArray(vertexNumber);
// debugger;
xPool.sort();
yPool.sort();
const minX = xPool[0];
const maxX = xPool[xPool.length - 1];
const minY = yPool[0];
const maxY = yPool[yPool.length - 1];
const xVec = []
const yVec = [];
let lastTop = minX;
let lastBot = minX;
xPool.forEach(x => {
if (Math.random() >= 0.5) {
xVec.push(x - lastTop);
lastTop = x;
} else {
xVec.push(lastBot - x);
lastBot = x;
}
});
xVec.push(maxX - lastTop);
xVec.push(lastBot - maxX);
let lastLeft = minY;
let lastRight = minY;
yPool.forEach(y => {
if (Math.random() >= 0.5) {
yVec.push(y - lastLeft);
lastLeft = y;
} else {
yVec.push(lastRight - y);
lastRight = y;
}
});
yVec.push(maxY - lastLeft);
yVec.push(lastRight - maxY);
shuffle(yVec);
vectors = [];
for (let i = 0; i < vertexNumber; ++i) {
vectors.push(new Point(xVec[i], yVec[i]));
}
vectors.sort((v1, v2) => {
if (Math.atan2(v1.y, v1.x) > Math.atan2(v2.y, v2.x)) {
return 1;
} else {
return -1;
}
});
let x = 0, y = 0;
let minPolygonX = 0;
let minPolygonY = 0;
let points = [];
for (let i = 0; i < vertexNumber; ++i) {
points.push(new Point(x, y));
x += vectors[i].x;
y += vectors[i].y;
minPolygonX = Math.min(minPolygonX, x);
minPolygonY = Math.min(minPolygonY, y);
}
// Move the polygon to the original min and max coordinates
let xShift = minX - minPolygonX;
let yShift = minY - minPolygonY;
for (let i = 0; i < vertexNumber; i++) {
const p = points[i];
points[i] = new Point(p.x + xShift, p.y + yShift);
}
return points;
}
function draw() {
const vertices = 10;
const _points = generateRandomConvexPolygon(vertices);
//apply scale
const points = _points.map(p => new Point(p.x * 300, p.y * 300));
const ctx = document.getElementById('drawpolygon').getContext('2d');
ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for(let i = 1; i < vertices ; ++i)
{
let x = points[i].x;
let y = points[i].y;
ctx.lineTo(x, y);
}
ctx.closePath();
ctx.fill();
}
draw();
<canvas id="drawpolygon"></canvas>
You could generate random points and then connect them with an approximate traveling salesman tour. Any tour that cannot be improved by 2-opt moves will not have edge crossings.
If it doesn't need to be random, here's a fast irregular n-point polygon:
Points are:
(0,0)
((i mod 2)+1, i) for 0 <= i <= n-2
Lines are between (0,0) and the two extreme points from the second row, as well as points generated by adjacent values of i.
I appreciate this is not strictly a code question - but I've not quite got to that point - let me explain...
I have a requirement to enable a user to draw (as simple freehand lines) onto an large image - and be able to zoom, pan and pinch (on an iPad).
This is driving me a bit crazy. I've looked at so many libraries, code samples, products etc and there seems to be nothing out there that meets this requirement i.e. drawing (one touch) WITH (multi-touch) pinch, zoom, pan. Lots of paint.net, signature captures etc, but nothing that supports the multi-touch bit.
I have tried to adapt various libraries to acheive what I want (e.g. combining an old version of sketch.js with hammer.js) but to be honest I've struggled. I do suspect that I will have to write my own at the end of the day and use something like hammer.js (excellent by the way) for gestures.
Anyway just in case someone out there has come across a library that might fit my needs or can point me in the right direction that would be appreciated.
Feel free to give me a hard time for avoiding coding it myself ;-)
Custom touch.
The example shows custom one touch draw and 2point pinch scale, rotate, pan using the standard browser touch events.
You need to prevent the standard gestures via the CSS rule touch-action: none; on the body of the document or it will not work.
Pointer
The pointer object which is initialised with
const pointer = setupPointingDevice(canvas);
Handles the touch. Use pointer.count to see how many touches there are, the first touch point is available as pointer.x, pointer.y. An array of touch points can be accessed as pointer.points[touchNumber]
View
The is an object at the bottom that handles the view. Its just a 2D matrix with some additional functions to handle the pinch. view.setPinch(point,point) starts the pinch with the 2 points as the reference. then view.movePinch(point,point) for updates
The view is used to draw the drawing canvas on the display canvas. To get the world (drawing coordinates) you need to convert from touch screen coordinates (canvas pixels) to the transformed drawing. Use view.toWorld(pointer.points[0]); to get the coordinates of the pinched drawing.
To set the main canvas transform use view.apply();
Not perfect
Humans tend to be sloppy and the interface to the touch zoom needs to delay drawing a little bit as the 2 touches for a pinch action may not happen at once. When a single touch is detected the app starts recording drawing points. If after several frames there is no second touch then it locks into drawing mode. No touch events are lost.
If a second touch occurs within several frames of the first it is assumed that a pinch action is being used. The app dumps any previous drawing points and set the mode to pinch.
When the app is in draw or pinch mode they are lock until no touches are detected. This is to prevent unwanted behaviour due to sloppy touching.
Demo
The demo is meant only as an example.
NOTE this will not function for non touch devices. I throw a error is no touch is found.
NOTE I have done only the most basic of agent detection. Android, and iPhones, iPads, and anything that reports multi touch.
NOTE Pinch events often result in two points dragging into one. This example does not handle such event correctly. You should switch to pan mode when a pinch gesture becomes a single touch and turn of rotate and scale.
const U = undefined;
const doFor = (count, callback) => {var i = 0; while (i < count && callback(i ++) !== true ); };
const drawModeDelay = 8; // number of frames to delay drawing just incase the pinch touch is
// slow on the second finger
const worldPoint = {x : 0, y : 0}; // worldf point is in the coordinates system of the drawing
const ctx = canvas.getContext("2d");
var drawMode = false; // true while drawing
var pinchMode = false; // true while pinching
var startup = true; // will call init when true
// the drawing image
const drawing = document.createElement("canvas");
const W = drawing.width = 512;
const H = drawing.height = 512;
const dCtx = drawing.getContext("2d");
dCtx.fillStyle = "white";
dCtx.fillRect(0,0,W,H);
// pointer is the interface to the touch
const pointer = setupPointingDevice(canvas);
ctx.font = "16px arial.";
if(pointer === undefined){
ctx.font = "16px arial.";
ctx.fillText("Did not detect pointing device. Demo terminated.", 20,20);
throw new Error("App Error : No touch found");
}
// drawing functions and data
const drawnPoints = []; // array of draw points
function drawOnDrawing(){ // draw all points on drawingPoint array
dCtx.fillStyle = "black";
while(drawnPoints.length > 0){
const point = drawnPoints.shift();
dCtx.beginPath();
dCtx.arc(point.x,point.y,8,0,Math.PI * 2);
dCtx.fill();
dCtx.stroke();
}
}
// called once at start
function init(){
startup = false;
view.setContext(ctx);
}
// standard vars
var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center
var ch = h / 2;
var globalTime;
// main update function
function update(timer){
if(startup){ init() };
globalTime = timer;
ctx.setTransform(1,0,0,1,0,0); // reset transform
ctx.globalAlpha = 1; // reset alpha
ctx.globalCompositeOperation = "source-over";
if(w !== innerWidth || h !== innerHeight){
cw = (w = canvas.width = innerWidth) / 2;
ch = (h = canvas.height = innerHeight) / 2;
}
// clear main canvas and draw the draw image with shadows and make it look nice
ctx.clearRect(0,0,w,h);
view.apply();
ctx.fillStyle = "black";
ctx.globalAlpha = 0.4;
ctx.fillRect(5,H,W-5,5)
ctx.fillRect(W,5,5,H);
ctx.globalAlpha = 1;
ctx.drawImage(drawing,0,0);
ctx.setTransform(1,0,0,1,0,0);
// handle touch.
// If single point then draw
if((pointer.count === 1 || drawMode) && ! pinchMode){
if(pointer.count === 0){
drawMode = false;
drawOnDrawing();
}else{
view.toWorld(pointer,worldPoint);
drawnPoints.push({x : worldPoint.x, y : worldPoint.y})
if(drawMode){
drawOnDrawing();
}else if(drawnPoints.length > drawModeDelay){
drawMode = true;
}
}
// if two point then pinch.
}else if(pointer.count === 2 || pinchMode){
drawnPoints.length = 0; // dump any draw points
if(pointer.count === 0){
pinchMode = false;
}else if(!pinchMode && pointer.count === 2){
pinchMode = true;
view.setPinch(pointer.points[0],pointer.points[1]);
}else{
view.movePinch(pointer.points[0],pointer.points[1]);
}
}else{
pinchMode = false;
drawMode = false;
}
requestAnimationFrame(update);
}
requestAnimationFrame(update);
function touch(element){
const touch = {
points : [],
x : 0, y : 0,
//isTouch : true, // use to determine the IO type.
count : 0,
w : 0, rx : 0, ry : 0,
}
var m = touch;
var t = touch.points;
function newTouch () { for(var j = 0; j < m.pCount; j ++) { if (t[j].id === -1) { return t[j] } } }
function getTouch(id) { for(var j = 0; j < m.pCount; j ++) { if (t[j].id === id) { return t[j] } } }
function setTouch(touchPoint,point,start,down){
if(touchPoint === undefined){ return }
if(start) {
touchPoint.oy = point.pageX;
touchPoint.ox = point.pageY;
touchPoint.id = point.identifier;
} else {
touchPoint.ox = touchPoint.x;
touchPoint.oy = touchPoint.y;
}
touchPoint.x = point.pageX;
touchPoint.y = point.pageY;
touchPoint.down = down;
if(!down) { touchPoint.id = -1 }
}
function mouseEmulator(){
var tCount = 0;
for(var j = 0; j < m.pCount; j ++){
if(t[j].id !== -1){
if(tCount === 0){
m.x = t[j].x;
m.y = t[j].y;
}
tCount += 1;
}
}
m.count= tCount;
}
function touchEvent(e){
var i, p;
p = e.changedTouches;
if (e.type === "touchstart") {
for (i = 0; i < p.length; i ++) { setTouch(newTouch(), p[i], true, true) }
} else if (e.type === "touchmove") {
for (i = 0; i < p.length; i ++) { setTouch(getTouch(p[i].identifier), p[i], false, true) }
} else if (e.type === "touchend") {
for (i = 0; i < p.length; i ++) { setTouch(getTouch(p[i].identifier), p[i], false, false) }
}
mouseEmulator();
e.preventDefault();
return false;
}
touch.pCount = navigator.maxTouchPoints;
element = element === undefined ? document : element;
doFor(navigator.maxTouchPoints, () => touch.points.push({x : 0, y : 0, dx : 0, dy : 0, down : false, id : -1}));
["touchstart","touchmove","touchend"].forEach(name => element.addEventListener(name, touchEvent) );
return touch;
}
function setupPointingDevice(element){
if(navigator.maxTouchPoints === undefined){
if(navigator.appVersion.indexOf("Android") > -1 ||
navigator.appVersion.indexOf("iPhone") > -1 ||
navigator.appVersion.indexOf("iPad") > -1 ){
navigator.maxTouchPoints = 5;
}
}
if(navigator.maxTouchPoints > 0){
return touch(element);
}else{
//return mouse(); // does not take an element defaults to the page.
}
}
const view = (()=>{
const matrix = [1,0,0,1,0,0]; // current view transform
const invMatrix = [1,0,0,1,0,0]; // current inverse view transform
var m = matrix; // alias
var im = invMatrix; // alias
var scale = 1; // current scale
var rotate = 0;
var maxScale = 1;
const pinch1 = {x :0, y : 0}; // holds the pinch origin used to pan zoom and rotate with two touch points
const pinch1R = {x :0, y : 0};
var pinchDist = 0;
var pinchScale = 1;
var pinchAngle = 0;
var pinchStartAngle = 0;
const workPoint1 = {x :0, y : 0};
const workPoint2 = {x :0, y : 0};
const wp1 = workPoint1; // alias
const wp2 = workPoint2; // alias
var ctx;
const pos = {x : 0,y : 0}; // current position of origin
var dirty = true;
const API = {
canvasDefault () { ctx.setTransform(1, 0, 0, 1, 0, 0) },
apply(){ if(dirty){ this.update() } ctx.setTransform(m[0], m[1], m[2], m[3], m[4], m[5]) },
reset() {
scale = 1;
rotate = 0;
pos.x = 0;
pos.y = 0;
dirty = true;
},
matrix,
invMatrix,
update () {
dirty = false;
m[3] = m[0] = Math.cos(rotate) * scale;
m[2] = -(m[1] = Math.sin(rotate) * scale);
m[4] = pos.x;
m[5] = pos.y;
this.invScale = 1 / scale;
var cross = m[0] * m[3] - m[1] * m[2];
im[0] = m[3] / cross;
im[1] = -m[1] / cross;
im[2] = -m[2] / cross;
im[3] = m[0] / cross;
},
toWorld (from,point = {}) { // convert screen to world coords
var xx, yy;
if (dirty) { this.update() }
xx = from.x - m[4];
yy = from.y - m[5];
point.x = xx * im[0] + yy * im[2];
point.y = xx * im[1] + yy * im[3];
return point;
},
toScreen (from,point = {}) { // convert world coords to screen coords
if (dirty) { this.update() }
point.x = from.x * m[0] + from.y * m[2] + m[4];
point.y = from.x * m[1] + from.y * m[3] + m[5];
return point;
},
setPinch(p1,p2){ // for pinch zoom rotate pan set start of pinch screen coords
if (dirty) { this.update() }
pinch1.x = p1.x;
pinch1.y = p1.y;
var x = (p2.x - pinch1.x);
var y = (p2.y - pinch1.y);
pinchDist = Math.sqrt(x * x + y * y);
pinchStartAngle = Math.atan2(y, x);
pinchScale = scale;
pinchAngle = rotate;
this.toWorld(pinch1, pinch1R)
},
movePinch(p1,p2,dontRotate){
if (dirty) { this.update() }
var x = (p2.x - p1.x);
var y = (p2.y - p1.y);
var pDist = Math.sqrt(x * x + y * y);
scale = pinchScale * (pDist / pinchDist);
if(!dontRotate){
var ang = Math.atan2(y, x);
rotate = pinchAngle + (ang - pinchStartAngle);
}
this.update();
pos.x = p1.x - pinch1R.x * m[0] - pinch1R.y * m[2];
pos.y = p1.y - pinch1R.x * m[1] - pinch1R.y * m[3];
dirty = true;
},
setContext (context) {ctx = context; dirty = true },
};
return API;
})();
canvas {
position : absolute;
top : 0px;
left : 0px;
z-index: 2;
}
body {
background:#bbb;
touch-action: none;
}
<canvas id="canvas"></canvas>
I am attempting to create a canvas web application and having two main problems. I would love to make the pen tool draw more smoothly. Secondly, each time I clear the sketch and begin to draw again the line begins in a different point to the curser/mouse.
Here is javascript for my drawing tool:
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var radius = 10;
var dragging = false;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context.lineWidth = radius*2;
var putPoint = function(e){
if(dragging){
context.lineTo(e.clientX, e.clientY);
context.stroke();
context.beginPath();
context.arc(e.clientX, e.clientY, radius, 0, Math.PI*2);
context.fill();
context.beginPath();
context.moveTo(e.clientX, e.clientY);
}}
var engage = function(){
dragging = true;
}
var disengage = function(){
dragging = false;
}
canvas.addEventListener('mousedown', engage);
canvas.addEventListener('mousemove', putPoint);
canvas.addEventListener('mouseup', disengage);
and this is how I am clearing the sketch:
// JavaScript Document
// bind event handler to clear button
document.getElementById('clear').addEventListener('click', function() {
context.clearRect(0, 0, canvas.width, canvas.height);
}, false);
A live preview can be seen at: http://www.sarahemily.net/canvas/
THANKS FOR YOUR HELP!
First the problem of the line starting in the wrong spot. You are forgetting to finish the path you create. You have beginPath, and moveTo but you leave it hanging. You need to call stroke once when the mouse button is up.
Smoothing.
Line smoothing is a very complicated thing to do with many professional drawing apps tackling the problem with a variety of solutions. There does not seem to be one agreed upon method. The big problem is.. How do you smooth a line but not destroy the desired line? and How do you do it quickly????
Here I present a two stage process.
Reduce the line complexity
Step one, reduce the line complexity. Sampling the mouse gives way to many points. So I need to reduce the number of points, but not lose any details.
I use the Ramer–Douglas–Peucker algorithm. It's quick and does a good job of reducing the complexity (number of points) of a line. Below you can find my implementation of the algorithm. It's not the best as it could do with some optimisation. You could most likely find it in some other language and port it to javascript.
It uses a recursive function to reduce complexity based on length and angle between line segments. At its core is the dot product of two line segments, it is a quick way of determining the angle between the two segments. See the supplied link above for more details.
// Line simplification based on
// the Ramer–Douglas–Peucker algorithm
// referance https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
// points: are and array of arrays consisting of [[x,y],[x,y],...,[x,y]]
// length: is in pixels and is the square of the actual distance.
// returns array of points of the same form as the input argument points.
var simplifyLineRDP = function(points, length) {
var simplify = function(start, end) { // recursive simplifies points from start to end
var maxDist, index, i, xx , yy, dx, dy, ddx, ddy, p1, p2, p, t, dist, dist1;
p1 = points[start];
p2 = points[end];
xx = p1[0];
yy = p1[1];
ddx = p2[0] - xx;
ddy = p2[1] - yy;
dist1 = (ddx * ddx + ddy * ddy);
maxDist = length;
for (var i = start + 1; i < end; i++) {
p = points[i];
if (ddx !== 0 || ddy !== 0) {
// dot product
t = ((p[0] - xx) * ddx + (p[1] - yy) * ddy) / dist1;
if (t > 1) {
dx = p[0] - p2[0];
dy = p[1] - p2[1];
} else
if (t > 0) {
dx = p[0] - (xx + ddx * t);
dy = p[1] - (yy + ddy * t);
} else {
dx = p[0] - xx;
dy = p[1] - yy;
}
}else{
dx = p[0] - xx;
dy = p[1] - yy;
}
dist = dx * dx + dy * dy
if (dist > maxDist) {
index = i;
maxDist = dist;
}
}
if (maxDist > length) { // continue simplification while maxDist > length
if (index - start > 1){
simplify(start, index);
}
newLine.push(points[index]);
if (end - index > 1){
simplify(index, end);
}
}
}
var end = points.length - 1;
var newLine = [points[0]];
simplify(0, end);
newLine.push(points[end]);
return newLine;
}
Smoothing using bezier curves
Next the smoothing. As the line has been simplified it if reasonably quick to then compare the angles between the many lines and create a bezier if the angle is below a required threshold.
Below is a example of how I do it. Though this will not fit the original line it is just concerned with smoothing. It is again a bit of a hack on my part and not based on any tried and tested algorithm. I have another one that does a bezier fit but that is too slow for the example.
Basicly it steps through the line segments and calculates the angle between two segments, if the angle is below the threshold it then adds bezier control points along the tangent of the two line segments, making either 2nd order or 3rd order beziers depending on whether two consecutive points are smoothed. This is a stripped down version of a much more complicated algorithm so excuse the mess.
// This is my own smoothing method The blindman`s smoother
// It creates a set of bezier control points either 2nd order or third order
// bezier curves.
// points: list of points [[x,y],[x,y],...,[x,y]]
// cornerThres: when to smooth corners and represents the angle between to lines.
// When the angle is smaller than the cornerThres then smooth.
// match: if true then the control points will be balanced.
// Function will make a copy of the points
// returns [[x,y],[x,y,bx,by],[x,y,b1x,b1y,b2x,b2y],.....] with x and y line points
// bx,by control points for 2nd order bezier and b1x,b1y,b2x,b2y the control
// points for 3rd order bezier. These are mixed as needed. Test the length of
// each point array to work out which bezier if any to use.
var smoothLine = function(points,cornerThres,match){ // adds bezier control points at points if lines have angle less than thres
var p1, p2, p3, dist1, dist2, x, y, endP, len, angle, i, newPoints, aLen, closed, bal, cont1, nx1, nx2, ny1, ny2, np;
function dot(x, y, xx, yy) { // get do product
// dist1,dist2,nx1,nx2,ny1,ny2 are the length and normals and used outside function
// normalise both vectors
dist1 = Math.sqrt(x * x + y * y); // get length
if (dist1 > 0) { // normalise
nx1 = x / dist1 ;
ny1 = y / dist1 ;
}else {
nx1 = 1; // need to have something so this will do as good as anything
ny1 = 0;
}
dist2 = Math.sqrt(xx * xx + yy * yy);
if (dist2 > 0) {
nx2 = xx / dist2;
ny2 = yy / dist2;
}else {
nx2 = 1;
ny2 = 0;
}
return Math.acos(nx1 * nx2 + ny1 * ny2 ); // dot product
}
newPoints = []; // array for new points
aLen = points.length;
if(aLen <= 2){ // nothing to if line too short
for(i = 0; i < aLen; i ++){ // ensure that the points are copied
newPoints.push([points[i][0],points[i][1]]);
}
return newPoints;
}
p1 = points[0];
endP =points[aLen-1];
i = 0; // start from second poitn if line not closed
closed = false;
len = Math.hypot(p1[0]- endP[0], p1[1]-endP[1]);
if(len < Math.SQRT2){ // end points are the same. Join them in coordinate space
endP = p1;
i = 0; // start from first point if line closed
p1 = points[aLen-2];
closed = true;
}
newPoints.push([points[i][0],points[i][1]])
for(; i < aLen-1; i++){
p2 = points[i];
p3 = points[i + 1];
angle = Math.abs(dot(p2[0] - p1[0], p2[1] - p1[1], p3[0] - p2[0], p3[1] - p2[1]));
if(dist1 !== 0){ // dist1 and dist2 come from dot function
if( angle < cornerThres*3.14){ // bend it if angle between lines is small
if(match){
dist1 = Math.min(dist1,dist2);
dist2 = dist1;
}
// use the two normalized vectors along the lines to create the tangent vector
x = (nx1 + nx2) / 2;
y = (ny1 + ny2) / 2;
len = Math.sqrt(x * x + y * y); // normalise the tangent
if(len === 0){
newPoints.push([p2[0],p2[1]]);
}else{
x /= len;
y /= len;
if(newPoints.length > 0){
var np = newPoints[newPoints.length-1];
np.push(p2[0]-x*dist1*0.25);
np.push(p2[1]-y*dist1*0.25);
}
newPoints.push([ // create the new point with the new bezier control points.
p2[0],
p2[1],
p2[0]+x*dist2*0.25,
p2[1]+y*dist2*0.25
]);
}
}else{
newPoints.push([p2[0],p2[1]]);
}
}
p1 = p2;
}
if(closed){ // if closed then copy first point to last.
p1 = [];
for(i = 0; i < newPoints[0].length; i++){
p1.push(newPoints[0][i]);
}
newPoints.push(p1);
}else{
newPoints.push([points[points.length-1][0],points[points.length-1][1]]);
}
return newPoints;
}
As I did not put that much thought into ease of use you will have to use the following function to render the resulting line.
var drawSmoothedLine = function(line){
var i,p;
ctx.beginPath()
ctx.moveTo(line[0][0],line[0][1])
for(i = 0; i < line.length-1; i++){
p = line[i];
p1 = line[i+1]
if(p.length === 2){ // linear
ctx.lineTo(p[0],p[1])
}else
if(p.length === 4){ // bezier 2nd order
ctx.quadraticCurveTo(p[2],p[3],p1[0],p1[1]);
}else{ // bezier 3rd order
ctx.bezierCurveTo(p[2],p[3],p[4],p[5],p1[0],p1[1]);
}
}
if(p.length === 2){
ctx.lineTo(p1[0],p1[1])
}
ctx.stroke();
}
So to use these to smooth a line. Simply capture the mouse points as you draw. When the done, then send the points to both functions in turn. Erase the drawn line and replace it with the new line. The is a bit of a lag between pen up and the smoothed result, but there is plenty of room for improvement in both functions.
To put it all together I have added a snippet below. The two bars at the top left control the smoothing and detail. The bottom bar controls the first function described above and the top controls the smoothing (bezier) the more red you see the smoother the lines and greater the detail reduction.
Middle mouse button clears or just restart.
Sorry, this was more work than I expected so the comments are a little sparse. I will improve the comments as time permits..
var canvas = document.getElementById("canV");
var ctx = canvas.getContext("2d");
// mouse stuff
var mouse = {
x:0,
y:0,
buttonLastRaw:0, // user modified value
buttonRaw:0,
buttons:[1,2,4,6,5,3], // masks for setting and clearing button raw bits;
};
function mouseMove(event){
mouse.x = event.offsetX; mouse.y = event.offsetY;
if(mouse.x === undefined){ mouse.x = event.clientX; mouse.y = event.clientY;}
if(event.type === "mousedown"){ mouse.buttonRaw |= mouse.buttons[event.which-1];
}else if(event.type === "mouseup"){mouse.buttonRaw &= mouse.buttons[event.which+2];
}else if(event.type === "mouseout"){ mouse.buttonRaw = 0; mouse.over = false;
}else if(event.type === "mouseover"){ mouse.over = true; }
event.preventDefault();
}
canvas.addEventListener('mousemove',mouseMove);
canvas.addEventListener('mousedown',mouseMove);
canvas.addEventListener('mouseup' ,mouseMove);
canvas.addEventListener('mouseout' ,mouseMove);
canvas.addEventListener('mouseover' ,mouseMove);
canvas.addEventListener("contextmenu", function(e){ e.preventDefault();}, false);
// Line simplification based on
// the Ramer–Douglas–Peucker algorithm
// referance https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
// points are and array of arrays consisting of [[x,y],[x,y],...,[x,y]]
// length is in pixels and is the square of the actual distance.
// returns array of points of the same form as the input argument points.
var simplifyLineRDP = function(points, length) {
var simplify = function(start, end) { // recursize simplifies points from start to end
var maxDist, index, i, xx , yy, dx, dy, ddx, ddy, p1, p2, p, t, dist, dist1;
p1 = points[start];
p2 = points[end];
xx = p1[0];
yy = p1[1];
ddx = p2[0] - xx;
ddy = p2[1] - yy;
dist1 = (ddx * ddx + ddy * ddy);
maxDist = length;
for (var i = start + 1; i < end; i++) {
p = points[i];
if (ddx !== 0 || ddy !== 0) {
t = ((p[0] - xx) * ddx + (p[1] - yy) * ddy) / dist1;
if (t > 1) {
dx = p[0] - p2[0];
dy = p[1] - p2[1];
} else
if (t > 0) {
dx = p[0] - (xx + ddx * t);
dy = p[1] - (yy + ddy * t);
} else {
dx = p[0] - xx;
dy = p[1] - yy;
}
}else{
dx = p[0] - xx;
dy = p[1] - yy;
}
dist = dx * dx + dy * dy
if (dist > maxDist) {
index = i;
maxDist = dist;
}
}
if (maxDist > length) { // continue simplification while maxDist > length
if (index - start > 1){
simplify(start, index);
}
newLine.push(points[index]);
if (end - index > 1){
simplify(index, end);
}
}
}
var end = points.length - 1;
var newLine = [points[0]];
simplify(0, end);
newLine.push(points[end]);
return newLine;
}
// This is my own smoothing method
// It creates a set of bezier control points either 2nd order or third order
// bezier curves.
// points: list of points
// cornerThres: when to smooth corners and represents the angle between to lines.
// When the angle is smaller than the cornerThres then smooth.
// match: if true then the control points will be balanced.
// Function will make a copy of the points
var smoothLine = function(points,cornerThres,match){ // adds bezier control points at points if lines have angle less than thres
var p1, p2, p3, dist1, dist2, x, y, endP, len, angle, i, newPoints, aLen, closed, bal, cont1, nx1, nx2, ny1, ny2, np;
function dot(x, y, xx, yy) { // get do product
// dist1,dist2,nx1,nx2,ny1,ny2 are the length and normals and used outside function
// normalise both vectors
dist1 = Math.sqrt(x * x + y * y); // get length
if (dist1 > 0) { // normalise
nx1 = x / dist1 ;
ny1 = y / dist1 ;
}else {
nx1 = 1; // need to have something so this will do as good as anything
ny1 = 0;
}
dist2 = Math.sqrt(xx * xx + yy * yy);
if (dist2 > 0) {
nx2 = xx / dist2;
ny2 = yy / dist2;
}else {
nx2 = 1;
ny2 = 0;
}
return Math.acos(nx1 * nx2 + ny1 * ny2 ); // dot product
}
newPoints = []; // array for new points
aLen = points.length;
if(aLen <= 2){ // nothing to if line too short
for(i = 0; i < aLen; i ++){ // ensure that the points are copied
newPoints.push([points[i][0],points[i][1]]);
}
return newPoints;
}
p1 = points[0];
endP =points[aLen-1];
i = 0; // start from second poitn if line not closed
closed = false;
len = Math.hypot(p1[0]- endP[0], p1[1]-endP[1]);
if(len < Math.SQRT2){ // end points are the same. Join them in coordinate space
endP = p1;
i = 0; // start from first point if line closed
p1 = points[aLen-2];
closed = true;
}
newPoints.push([points[i][0],points[i][1]])
for(; i < aLen-1; i++){
p2 = points[i];
p3 = points[i + 1];
angle = Math.abs(dot(p2[0] - p1[0], p2[1] - p1[1], p3[0] - p2[0], p3[1] - p2[1]));
if(dist1 !== 0){ // dist1 and dist2 come from dot function
if( angle < cornerThres*3.14){ // bend it if angle between lines is small
if(match){
dist1 = Math.min(dist1,dist2);
dist2 = dist1;
}
// use the two normalized vectors along the lines to create the tangent vector
x = (nx1 + nx2) / 2;
y = (ny1 + ny2) / 2;
len = Math.sqrt(x * x + y * y); // normalise the tangent
if(len === 0){
newPoints.push([p2[0],p2[1]]);
}else{
x /= len;
y /= len;
if(newPoints.length > 0){
var np = newPoints[newPoints.length-1];
np.push(p2[0]-x*dist1*0.25);
np.push(p2[1]-y*dist1*0.25);
}
newPoints.push([ // create the new point with the new bezier control points.
p2[0],
p2[1],
p2[0]+x*dist2*0.25,
p2[1]+y*dist2*0.25
]);
}
}else{
newPoints.push([p2[0],p2[1]]);
}
}
p1 = p2;
}
if(closed){ // if closed then copy first point to last.
p1 = [];
for(i = 0; i < newPoints[0].length; i++){
p1.push(newPoints[0][i]);
}
newPoints.push(p1);
}else{
newPoints.push([points[points.length-1][0],points[points.length-1][1]]);
}
return newPoints;
}
// creates a drawable image
var createImage = function(w,h){
var image = document.createElement("canvas");
image.width = w;
image.height =h;
image.ctx = image.getContext("2d");
return image;
}
// draws the smoothed line with bezier control points.
var drawSmoothedLine = function(line){
var i,p;
ctx.beginPath()
ctx.moveTo(line[0][0],line[0][1])
for(i = 0; i < line.length-1; i++){
p = line[i];
p1 = line[i+1]
if(p.length === 2){ // linear
ctx.lineTo(p[0],p[1])
}else
if(p.length === 4){ // bezier 2nd order
ctx.quadraticCurveTo(p[2],p[3],p1[0],p1[1]);
}else{ // bezier 3rd order
ctx.bezierCurveTo(p[2],p[3],p[4],p[5],p1[0],p1[1]);
}
}
if(p.length === 2){
ctx.lineTo(p1[0],p1[1])
}
ctx.stroke();
}
// smoothing settings
var lineSmooth = {};
lineSmooth.lengthMin = 8; // square of the pixel length
lineSmooth.angle = 0.8; // angle threshold
lineSmooth.match = false; // not working.
// back buffer to save the canvas allowing the new line to be erased
var backBuffer = createImage(canvas.width,canvas.height);
var currentLine = [];
mouse.lastButtonRaw = 0; // add mouse last incase not there
ctx.lineWidth = 3;
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.strokeStyle = "black";
ctx.clearRect(0,0,canvas.width,canvas.height);
var drawing = false; // if drawing
var input = false; // if menu input
var smoothIt = false; // flag to allow feedback that smoothing is happening as it takes some time.
function draw(){
// if not drawing test for menu interaction and draw the menus
if(!drawing){
if(mouse.x < 203 && mouse.y < 24){
if(mouse.y < 13){
if(mouse.buttonRaw === 1){
ctx.clearRect(3,3,200,10);
lineSmooth.angle = (mouse.x-3)/200;
input = true;
}
}else
if(mouse.buttonRaw === 1){
ctx.clearRect(3,14,200,10);
lineSmooth.lengthMin = (mouse.x-3)/10;
input = true;
}
canvas.style.cursor = "pointer";
}else{
canvas.style.cursor = "crosshair";
}
if(mouse.buttonRaw === 0 && input){
input = false;
mouse.lastButtonRaw = 0;
}
ctx.lineWidth = 1;
ctx.fillStyle = "red";
ctx.fillRect(3,3,lineSmooth.angle*200,10);
ctx.fillRect(3,14,lineSmooth.lengthMin*10,10);
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillStyle = "#5F2"
ctx.strokeRect(3,3,200,10);
ctx.fillText("Smooth",5,2)
ctx.strokeRect(3,14,200,10);
ctx.fillText("Detail",5,13);
}else{
canvas.style.cursor = "crosshair";
}
if(!input){
ctx.lineWidth = 3;
if(mouse.buttonRaw === 1 && mouse.lastButtonRaw === 0){
currentLine = [];
drawing = true;
backBuffer.ctx.clearRect(0,0,canvas.width,canvas.height);
backBuffer.ctx.drawImage(canvas,0,0);
currentLine.push([mouse.x,mouse.y])
}else
if(mouse.buttonRaw === 1){
var lp = currentLine[currentLine.length-1]; // get last point
// dont record point if no movement
if(mouse.x !== lp[0] || mouse.y !== lp[1] ){
currentLine.push([mouse.x,mouse.y]);
ctx.beginPath();
ctx.moveTo(lp[0],lp[1])
ctx.lineTo(mouse.x,mouse.y);
ctx.stroke();
}
}else
if(mouse.buttonRaw === 0 && mouse.lastButtonRaw === 1){
ctx.textAlign = "center"
ctx.fillStyle = "red"
ctx.fillText("Smoothing...",canvas.width/2,canvas.height/5);
smoothIt = true;
}else
if(smoothIt){
smoothIt = false;
var newLine = smoothLine(
simplifyLineRDP(
currentLine,
lineSmooth.lengthMin
),
lineSmooth.angle,
lineSmooth.match
);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(backBuffer,0,0);
drawSmoothedLine(newLine);
drawing = false;
}
}
// middle button clear
if(mouse.buttonRaw === 2){
ctx.clearRect(0,0,canvas.width,canvas.height);
}
mouse.lastButtonRaw = mouse.buttonRaw;
requestAnimationFrame(draw);
}
draw();
.canC { width:1000px; height:500px;}
<canvas class="canC" id="canV" width=1000 height=500></canvas>
I would love to make the pen tool draw more smoothly
Use can use quadratic curves instead of lines:
ctx.quadraticCurveTo(cpx, cpy, x, y);
Example: http://www.w3schools.com/tags/canvas_quadraticcurveto.asp
JS fiddle
I have a coordinates array populated by mouse clicks on a canvas.
var pointsArray = [];
This array is pushed x and y values using a click event.
pointsArray.push({x: xVal, y: yVal});
I iterate the points array and draw a line between the current point, and the previous point.
function drawPolygon(points) {
//check arguments for null values
if(!points)
return false;
var i;
for(i = 0; i < points.length; i++)
drawLine(points[i-1], points[i]);
//draw the final line
drawLine(points[i-1], points[0]);
}
drawLine looks like this:
function drawLine(point1, point2) {
//check arguments for null values
if(!point1 || !point2)
return false;
context.beginPath();
context.moveTo(point1.x, point1.y);
context.lineTo(point2.x, point2.y);
context.stroke();
}
Unfortunately, depending on what order the users click, I can have the lines intersect, which I don't want: http://i.imgur.com/3gaHRTa.png How would I solve for this? My first instinct tells me to order the points top-to-bottom, left-to-right in the array then draw.
Step 1: Find center of polygon using average position of points
This function will find the center given all the points in the drawing, independent of order:
function findCenter(points) {
var x = 0, y = 0, i, len = points.length;
for (i = 0; i < len; i++) {
x += points[i].x;
y += points[i].y;
}
return {x: x / len, y: y / len}; // return average position
}
Demo showing center point in polygon
/**
* Created by knguyen on 4/13/2015.
*/
var pointsArray = [];
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
function Point(x, y) {
this.x = x;
this.y = y;
}
function drawDot(e) {
var position = getMousePosition(canvas, e);
posx = position.x;
posy = position.y;
storeCoordinate(posx, posy);
context.fillStyle = "#F00";
context.fillRect(posx, posy, 6, 6);
}
function getMousePosition(c, e) {
var rect = canvas.getBoundingClientRect();
return {x: e.clientX - rect.left, y: e.clientY - rect.top}
}
function storeCoordinate(xVal, yVal) {pointsArray.push(new Point(xVal, yVal))}
$("#solve").click(
function() {
var p = findCenter(pointsArray);
context.fillStyle = "green";
context.fillRect(p.x, p.y, 4, 4);
}
);
function findCenter(points) {
var x = 0, y = 0, i, len = points.length;
for (i = 0; i < len; i++) {
x += points[i].x;
y += points[i].y;
}
return {x: x / len, y: y / len}; // return average position
}
#myCanvas {border: 1px solid #000}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myCanvas" width="400" height="300" onclick="drawDot(event)"></canvas>
<div>
<button type="button" class="btn btn-default" id="solve">Show center point</button>
</div>
Step 2: Sort points based on angle
Extend the point object to also take an angle argument.
Iterate trough the point array
Calculate the angle relative to the center point
Sort array based on angle
To find the angles just calculate the angle relative to the center point.
Here is how:
function findAngles(c, points) {
var i, len = points.length, p, dx, dy;
for (i = 0; i < len; i++) {
p = points[i];
dx = p.x - c.x;
dy = p.y - c.y;
p.angle = Math.atan2(dy, dx);
}
}
Then you have to sort the points based on angle using a custom sort function. Just use the standard sort() method on the array and supply your own function which will use the angle property of the point object:
pointsArray.sort(function(a, b) {
if (a.angle > b.angle) return 1;
else if (a.angle < b.angle) return -1;
return 0;
});
Then draw a line between all the points.
Working Demo
var pointsArray = [];
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
function Point(x, y) {
this.x = x;
this.y = y;
this.angle = 0;
}
canvas.onclick = drawDot;
function drawDot(e) {
var position = getMousePosition(canvas, e);
posx = position.x;
posy = position.y;
storeCoordinate(posx, posy);
context.fillStyle = "#F00";
context.fillRect(posx-3, posy-3, 6, 6);
}
function getMousePosition(c, e) {
var rect = canvas.getBoundingClientRect();
return {x: e.clientX - rect.left, y: e.clientY - rect.top}
}
function storeCoordinate(xVal, yVal) {pointsArray.push(new Point(xVal, yVal))}
$("#solve").click(
function() {
// find center
var cent = findCenter(pointsArray);
context.fillStyle = "green";
context.fillRect(cent.x-3, cent.y-3, 6, 6);
// find angles
findAngles(cent, pointsArray);
// sort based on angle using custom sort
pointsArray.sort(function(a, b) {
return (a.angle >= b.angle) ? 1 : -1
});
// draw lines
context.beginPath();
context.moveTo(pointsArray[0].x, pointsArray[0].y);
for(var i = 0; i < pointsArray.length; i++) {
context.lineTo(pointsArray[i].x, pointsArray[i].y);
}
context.strokeStyle = "#00f";
context.closePath();
context.stroke();
}
);
function findCenter(points) {
var x = 0, y = 0, i, len = points.length;
for (i = 0; i < len; i++) {
x += points[i].x;
y += points[i].y;
}
return {x: x / len, y: y / len}; // return average position
}
function findAngles(c, points) {
var i, len = points.length, p, dx, dy;
for (i = 0; i < len; i++) {
p = points[i];
dx = p.x - c.x;
dy = p.y - c.y;
p.angle = Math.atan2(dy, dx);
}
}
$("#reset").click(
function() {
context.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
pointsArray = []; //clear the array
}
);
#myCanvas {border: 1px solid #000}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myCanvas" width="400" height="300"></canvas>
<div><button id="solve">Draw Polygon</button><button id="reset">Reset</button></div>
Polygons are said to be defined clockwise or counter-clockwise manner.
To sort your "random" clicks into clockwise order:
Find the "center" of your polygon. This is the arithmetic mean of the x's and y's.
Calculate all the angles from the centerpoint to each of your user's points. You can do this using Math.atan2(differenceInYs,differenceInXs);
Sort the points in ascending order by their angles calculated in #2.
Your points now form a clockwise polygon.