HTML5 Canvas Javascript how to make smooth brush - javascript

Hello i need make smooth brush likes this:
I try to create it, i make circle and fill it, but result not successful:
Can be seen circles.. this is not smooth like first example
my example code:
function distanceBetween(point1, point2) {
return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));
}
function angleBetween(point1, point2) {
return Math.atan2( point2.x - point1.x, point2.y - point1.y );
}
var el = document.getElementById('c');
var ctx = el.getContext('2d');
//ctx.fillStyle = "rgba('255, 0, 0, 0.1')";
ctx.fillStyle = "red";
ctx.strokeStyle = "red";
ctx.globalAlpha = "0.05";
ctx.lineWidth = 0;
ctx.globalCompositeOperation = "source-over";
var isDrawing, lastPoint;
el.onmousedown = function(e) {
isDrawing = true;
lastPoint = { x: e.clientX, y: e.clientY };
};
el.onmousemove = function(e) {
if (!isDrawing) return;
var currentPoint = { x: e.clientX, y: e.clientY };
var dist = distanceBetween(lastPoint, currentPoint);
var angle = angleBetween(lastPoint, currentPoint);
for (var i = 0; i < dist; i+=5) {
x = lastPoint.x + (Math.sin(angle) * i) - 25;
y = lastPoint.y + (Math.cos(angle) * i) - 25;
ctx.beginPath();
ctx.arc(x+10, y+10, 20, false, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
lastPoint = currentPoint;
};
el.onmouseup = function() {
isDrawing = false;
};
function clearit() {
ctx.clearRect(0,0, 1000, 1000);
}
canvas { border: 1px solid #ccc }
<canvas id="c" width="500" height="300"></canvas>
<input type="button" id="clear-btn" value="Clear it" onclick="clearit()">
http://codepen.io/anon/pen/NPjwry

Try with a smaller globalAlpha and decrease the stepping (so you draw more circles)
function distanceBetween(point1, point2) {
return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));
}
function angleBetween(point1, point2) {
return Math.atan2( point2.x - point1.x, point2.y - point1.y );
}
var el = document.getElementById('c');
var ctx = el.getContext('2d');
//ctx.fillStyle = "rgba('255, 0, 0, 0.1')";
ctx.fillStyle = "red";
ctx.strokeStyle = "red";
ctx.globalAlpha = "0.01";
ctx.lineWidth = 0;
ctx.globalCompositeOperation = "source-over";
var isDrawing, lastPoint;
el.onmousedown = function(e) {
isDrawing = true;
lastPoint = { x: e.clientX, y: e.clientY };
};
el.onmousemove = function(e) {
if (!isDrawing) return;
var currentPoint = { x: e.clientX, y: e.clientY };
var dist = distanceBetween(lastPoint, currentPoint);
var angle = angleBetween(lastPoint, currentPoint);
for (var i = 0; i < dist; i+=3) {
x = lastPoint.x + (Math.sin(angle) * i) - 25;
y = lastPoint.y + (Math.cos(angle) * i) - 25;
ctx.beginPath();
ctx.arc(x+10, y+10, 20, false, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
lastPoint = currentPoint;
};
el.onmouseup = function() {
isDrawing = false;
};
function clearit() {
ctx.clearRect(0,0, 1000, 1000);
}
canvas { border: 1px solid #ccc }
<canvas id="c" width="500" height="300"></canvas>
<input type="button" id="clear-btn" value="Clear it" onclick="clearit()">
Updated codepen: http://codepen.io/gpetrioli/pen/ramqBz

There is more simple solution: just set width of line to 25px
let ctx = this.d.transparentUpdateImage.getContext('2d');
if (!this.lastPos) {
this.lastPos = {x: x, y: y};
return
}
ctx.beginPath();
ctx.moveTo(this.lastPos.x, this.lastPos.y);
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.strokeStyle = 'red';
ctx.lineWidth = 25;
ctx.lineTo(x, y);
ctx.stroke();
ctx.closePath();
this.lastPos = {x: x, y: y};

Related

Using Canvas to draw multiple polygons but can not get color to be different for polygons

I an issue with the implementation of drawing multiple polygons on a canvas.
I draw the two polygons,
when I move the mouse into the 2nd polygon it turns red and so does the first polygon (the first polygon should be blue). When I move the mouse into the 1st polygon it turns red and so does the 2nd polygon (the 2nd polygon should be blue).
I found the issue with research of each canvas call; adding a ctx.beginPath() fixed the issue. See below:
<canvas id="myCanvas" width=600 height=600 ></canvas>
<script>
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
myimage = new Image();
myimage.src = 'https://i.postimg.cc/SNjPPZGJ/farms-map.png';
myimage.onload = draw
const rect = canvas.getBoundingClientRect();
const polypoints1 = [{x: 200, y: 29}, {x: 500, y: 19}, {x: 465, y: 146}, {x: 130, y: 150}];
const polypoints2 = [{x: 200, y: 229}, {x: 500, y: 219}, {x: 465, y: 346}, {x: 130, y: 350}];
var polyColor = [];
var dragPoint = null;
draw();
canvas.addEventListener('mousedown', onMouseDown);
canvas.addEventListener('mousemove', function(evt) {
polyColor[0]="blue";
polyColor[1]="blue";
if (inside({x:evt.clientX - rect.left, y:(evt.clientY + window.scrollY) - rect.top}, polypoints1)){
polyColor[0]="red";
polyColor[1]="blue";}
if (inside({x:evt.clientX - rect.left, y:(evt.clientY + window.scrollY) - rect.top}, polypoints2)){
polyColor[0]="blue";
polyColor[1]="red";}
draw()
}, false);
function inside(p, vs) {
var inside = false;
for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
var xi = vs[i].x, yi = vs[i].y;
var xj = vs[j].x, yj = vs[j].y;
var intersect = ((yi > p.y) != (yj > p.y)) && (p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
};
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (myimage) {
ctx.drawImage(myimage, 1, 1)
}
drawLines();
polypoints1.forEach(p => drawPoint(p));
polypoints2.forEach(p => drawPoint(p));
}
function drawPoint(p) {
ctx.beginPath();
ctx.globalAlpha = 1
ctx.fillStyle = "black";
ctx.lineWidth = 2;
ctx.arc(p.x, p.y, 5, 0, 2 * Math.PI, false);
ctx.stroke();
ctx.fill();
}
function drawLines() {
ctx.beginPath();
ctx.lineWidth = 2;
polypoints1.forEach(p => ctx.lineTo(p.x, p.y));
ctx.lineTo(polypoints1[0].x, polypoints1[0].y);
ctx.stroke();
if (!dragPoint) {
ctx.globalAlpha = 0.2
ctx.fillStyle = polyColor[0];
ctx.fill();
}
ctx.beginPath();
ctx.lineWidth = 2;
polypoints2.forEach(p => ctx.lineTo(p.x, p.y));
ctx.lineTo(polypoints2[0].x, polypoints2[0].y);
ctx.stroke();
if (!dragPoint) {
ctx.globalAlpha = 0.2
ctx.fillStyle = polyColor[1];
ctx.fill();
}
}
function findDragPoint(x, y) {
for (i = 0; i < polypoints1.length; i++) {
if (hitTest(polypoints1[i], x, y)) return polypoints1[i];
if (hitTest(polypoints2[i], x, y)) return polypoints2[i];
};
return null;
}
function onMouseDown(event) {
dragPoint = findDragPoint(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop + window.scrollY);
if (dragPoint) {
dragPoint.x = event.clientX - canvas.offsetLeft;
dragPoint.y = event.clientY - canvas.offsetTop + window.scrollY;
draw();
canvas.addEventListener("mousemove", onMouseMove);
canvas.addEventListener("mouseup", onMouseUp);
}
}
function onMouseMove(event) {
dragPoint.x = event.clientX - canvas.offsetLeft;
dragPoint.y = event.clientY - canvas.offsetTop+ window.scrollY;
draw();
}
function onMouseUp() {
dragPoint = null;
draw();
canvas.removeEventListener("mousemove", onMouseMove);
canvas.removeEventListener("mouseup", onMouseUp);
}
function hitTest(p, x, y) {
var dx = p.x - x, dy = p.y - y;
return Math.sqrt(dx * dx + dy * dy) <= 10;
}
</script>
I found that you have to use ctx.beginPath() before you start to set up the second polygon. This seems to have addressed the issue.

Determine the distance between a straight line and a curve line drawn in a HTML canvas

I have a program in HTML, CSS and JavaScript where one can draw a from an initial point (Mousedown event )curved line(Mousemove event) and a straight line when the mouse click is lifted up(MouseUp event).
Now my problem is finding the distance of the curve line and as well as the straight line in two different labels.
My code goes below
var canvas = document.querySelector('#paint');
var ctx = canvas.getContext('2d');
var sketch = document.querySelector('#sketch');
var sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
var mouse = {
x: 0,
y: 0
};
var last_mouse = {
x: 0,
y: 0
};
/* Mouse Capturing Work */
canvas.addEventListener('mousemove', function(e) {
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
/* Drawing on Paint App */
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'black';
canvas.addEventListener('mousedown', function(e) {
initialPoint = {
x: mouse.x,
y: mouse.y
}
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
drawStraightLine()
canvas.removeEventListener('mousemove', onPaint, false);
}, false);
var onPaint = function() {
ctx.beginPath();
ctx.moveTo(last_mouse.x, last_mouse.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.strokeStyle = "#000000";
ctx.closePath();
ctx.stroke();
};
let initialPoint
const drawStraightLine = function() {
ctx.beginPath();
ctx.moveTo(initialPoint.x, initialPoint.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.strokeStyle = "#FF000077";
ctx.stroke();
}
html,
body {
width: 80%;
height: 50%;
}
#sketch {
border: 10px solid gray;
height: 100%;
}
<div id="sketch">
<canvas id="paint"></canvas>
<script src="1.js"></script>
</div>
<label id="StraightLineDistance"></label>
<label id="CurvedLineDistance"></label>
To find the length of a line you use Pythagoras
Eg the distance between two points A, B
function distanceBetween(A, B) {
return ((B.x - A.x) ** 2 + (B.y - A.y) ** 2) ** 0.5;
}
Or
function distanceBetween(A, B) {
const dx = B.x - A.x;
const dy = B.y - A.y;
return Math.sqrt(dx * dx + dy * dy);
}
Or
function distanceBetween(A, B) {
return Math.hypot(B.x - A.x, B.y - A.y);
}
To measure the drawn path you will need to accumulate the length each sub path (line) to get a total.
Example
The example accumulates the length as it is drawn. When the mouse down event happens the accumulated length is zeroed.
const canvas = document.querySelector('#paint');
const ctx = canvas.getContext('2d');
const sketch = document.querySelector('#sketch');
const sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
var pathLength = 0;
var distance = 0;
const mouse = {x: 0, y: 0};
const last_mouse = {x: 0, y: 0};
const initialPoint = {x: 0, y: 0};
function distanceBetween(A, B) {
const dx = B.x - A.x;
const dy = B.y - A.y;
return (dx * dx + dy * dy) ** 0.5;
}
/* Drawing on Paint App */
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'black';
canvas.addEventListener('mousedown', function(e) {
initialPoint.x = mouse.x = e.pageX - this.offsetLeft;
initialPoint.y = mouse.y = e.pageY - this.offsetTop;
pathLength = 0;
canvas.addEventListener('mousemove', onPaint);
}, false);
canvas.addEventListener('mouseup', function() {
drawStraightLine()
canvas.removeEventListener('mousemove', onPaint);
}, false);
function displayLengths() {
StraightLineDistance.textContent = "Distance: " + distance.toFixed(0) + "px";
CurvedLineDistance.textContent = "Traveled: " + pathLength.toFixed(0) + "px";
}
function onPaint(e) {
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.lineTo(last_mouse.x, last_mouse.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
pathLength += distanceBetween(last_mouse, mouse);
distance = distanceBetween(initialPoint, mouse);
displayLengths();
};
function drawStraightLine() {
ctx.strokeStyle = "#FF000077";
ctx.beginPath();
ctx.lineTo(initialPoint.x, initialPoint.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
distance = distanceBetween(initialPoint, mouse);
displayLengths();
}
html,
body {
width: 80%;
height: 50%;
}
#sketch {
border: 10px solid gray;
height: 100%;
}
<div id="sketch">
<canvas id="paint"></canvas>
<script src="1.js"></script>
</div>
<label id="StraightLineDistance"></label>
<label id="CurvedLineDistance"></label>
The JavaScript file
const canvas = document.querySelector('#paint');
const ctx = canvas.getContext('2d');
const sketch = document.querySelector('#sketch');
const sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
var pathLength = 0;
var distance = 0;
const mouse = {x: 0, y: 0};
const last_mouse = {x: 0, y: 0};
const initialPoint = {x: 0, y: 0};
function distanceBetween(A, B) {
const dx = B.x - A.x;
const dy = B.y - A.y;
return (dx * dx + dy * dy) ** 0.5;
}
/* Drawing on Paint App */
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'black';
canvas.addEventListener('mousedown', function(e) {
initialPoint.x = mouse.x = e.pageX - this.offsetLeft;
initialPoint.y = mouse.y = e.pageY - this.offsetTop;
pathLength = 0;
canvas.addEventListener('mousemove', onPaint);
}, false);
canvas.addEventListener('mouseup', function() {
drawStraightLine()
canvas.removeEventListener('mousemove', onPaint);
}, false);
function displayLengths() {
StraightLineDistance.textContent = "Distance: " + distance.toFixed(0) + "px";
CurvedLineDistance.textContent = "Traveled: " + pathLength.toFixed(0) + "px";
}
function onPaint(e) {
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.lineTo(last_mouse.x, last_mouse.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
pathLength += distanceBetween(last_mouse, mouse);
distance = distanceBetween(initialPoint, mouse);
displayLengths();
};
function drawStraightLine() {
ctx.strokeStyle = "#FF000077";
ctx.beginPath();
ctx.lineTo(initialPoint.x, initialPoint.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
distance = distanceBetween(initialPoint, mouse);
displayLengths();
}
The HTML file
<link rel="stylesheet" href="1.css"/>
</head>
<body>
<div id="sketch">
<canvas id="paint"></canvas>
<script src="1.js"></script>
</div>
<label id="StraightLineDistance"></label><br/>
<label id="CurvedLineDistance"></label><br/>
<label id="Index"></label>
</body>
</html>
My new doubt is how can I show the realtime value of ratio of (distance/pathLength) in the label id="Index"
I have tried using Index.textContent = (distance/pathLength).toFixed(0); but that shows 1 and its constant in the output.
I would be pleased if I am helped with this

Dragging a circle on a canvas using mousedown

Right now, I have 2 circles and a line in between. I want to be able to drag one of the circles with the line still attached and it will stay connected to the circle as I move it.
The node1 and node2 are the circle dimensions. The line/muscle is connected to node1 and node2's x and y position.
function draw() {
//draw in the container
c.fillStyle = "#000000";
c.fillRect(container.y, container.x, container.width, container.height);
//draw first node
c.arc(node1.x, node1.y, node1.r, 0, 2*Math.PI);
c.fillStyle = node1.color;
c.fill();
//draw second node
c.arc(node2.x, node2.y, node2.r, 0, 2*Math.PI);
c.strokeStyle = node2.color;
c.fillStyle = node2.color;
c.fill();
//draw muscle
c.beginPath();
c.moveTo(muscle.node1x, muscle.node1y);
c.lineTo(muscle.node2x, muscle.node2y);
c.strokeStyle = muscle.color;
c.lineWidth = muscle.width;
c.stroke();
}
How the project looks so far
The following code is based on your draw function and implements the drag function.
function draw(container, c, node1, node2, muscle) {
//draw in the container
c.fillStyle = "#000000";
c.fillRect(container.y, container.x, container.width, container.height);
//draw first node
c.arc(node1.x, node1.y, node1.r, 0, 2 * Math.PI);
c.fillStyle = node1.color;
c.closePath();
c.fill();
//draw second node
c.arc(node2.x, node2.y, node2.r, 0, 2 * Math.PI);
c.strokeStyle = node2.color;
c.fillStyle = node2.color;
c.closePath();
c.fill();
//draw muscle
c.beginPath();
c.moveTo(muscle.node1x, muscle.node1y);
c.lineTo(muscle.node2x, muscle.node2y);
c.strokeStyle = muscle.color;
c.lineWidth = muscle.width;
c.closePath();
c.stroke();
}
function Node(x, y, r, color) {
this.x = x;
this.y = y;
this.r = r || 20;
this.color = color || "#ff0";
}
function Muscle(node1, node2, width, color) {
this.node1 = node1;
this.node2 = node2;
this.width = width || 5;
this.color = color || "#f00";
Object.defineProperties(this, {
node1x: {
"get": () => this.node1.x,
"set": x => { this.node1.x = x }
},
node1y: {
"get": () => this.node1.y,
"set": y => { this.node1.y = y }
},
node2x: {
"get": () => this.node2.x,
"set": x => { this.node2.x = x }
},
node2y: {
"get": () => this.node2.y,
"set": y => { this.node2.y = y }
}
})
}
function handleMouseDrag(canvas, nodes) {
var isDrag = false;
var offset = { x: 0, y: 0, x0: 0, y0: 0 };
var dragNode = undefined;
canvas.addEventListener("mousedown", function (e) {
var x = e.offsetX, y = e.offsetY;
for (var i in nodes) {
if (Math.pow(x - nodes[i].x, 2) + Math.pow(y - nodes[i].y, 2) < Math.pow(nodes[i].r, 2)) {
isDrag = true;
dragNode = nodes[i];
offset = { x: dragNode.x, y: dragNode.y, x0: x, y0: y };
return;
}
}
});
canvas.addEventListener("mousemove", function (e) {
if (isDrag) {
dragNode.x = e.offsetX - offset.x0 + offset.x;
dragNode.y = e.offsetY - offset.y0 + offset.y;
}
});
canvas.addEventListener("mouseup", function (e) {
isDrag = false;
});
canvas.addEventListener("mouseleave", function (e) {
isDrag = false;
});
}
function main() {
var node1 = new Node(40, 40);
var node2 = new Node(120, 120);
var muscle = new Muscle(node1, node2);
var canvas = document.getElementById("canvas");
var container = { x: 0, y: 0, get width() { return canvas.width }, get height() { return canvas.height } }
var ctx = canvas.getContext("2d");
handleMouseDrag(canvas, [node1, node2]);
function updateFrame() {
ctx.save();
draw(container, ctx, node1, node2, muscle);
ctx.restore();
requestAnimationFrame(updateFrame)
};
updateFrame();
}
main();
<canvas width="400" height="400" id="canvas"></canvas>

HTML5 canvas paint redrawing lineJoin not rounded

Hello i make like a paint with undo function, i write all coordinates in array and then try undo just redrawing without last coordinates but problem while i redrawing my canvas parameters incorrect. i use lineJoin = "roind" but after redrawing i see without round..
this result with round line begin and line end while i drawing:
this result without round begin and line end after undo function:
I don't have idea where disappear my round lines while i redrawing all drawings coordinate by coordinate..
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var points = [];
var size = 10;
var prevX = 0;
var prevY = 0;
var isCanDraw = false;
$("#canvas").on("mousedown", function(e) {
isCanDraw = true;
prevX = e.clientX;
prevY = e.clientY;
points.push({x: prevX, y: prevY, size: size, mode: "begin"});
});
$("#canvas").on("mousemove", function(e) {
if(isCanDraw) {
stroke(e.clientX, e.clientY);
points.push({x: prevX, y: prevY, size: size, mode: "draw"});
}
});
$("#canvas").on("mouseup", function(e) {
isCanDraw = false;
points.push({x: prevX, y: prevY, size: size, mode: "end"});
});
$("#canvas").on("mouseleave", function(e) {
isCanDraw = false;
});
$("#undo").on("click", function(e) {
deleteLast();
redraw();
});
function deleteLast() {
if(points.length != 0) {
var i = points.length - 1;
while(points[i].mode != "begin") {
i--;
points.pop();
}
points.pop();
}
}
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if(points.length != 0) {
for(var i=0; i < points.length; i++) {
var pt = points[i];
var begin=false;
if(size != pt.size) {
size = pt.size;
begin=true;
}
if(pt.mode == "begin" || begin) {
ctx.moveTo(pt.x, pt.y)
}
ctx.lineTo(pt.x, pt.y)
if( pt.mode == "end" || (i == points.length-1) ) {
ctx.lineJoin = "round";
ctx.stroke()
}
}
}
}
function stroke(x,y) {
ctx.lineWidth = size;
ctx.lineJoin = "round";
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(x, y);
ctx.closePath();
ctx.stroke();
prevX = x;
prevY = y;
}
#canvas {
border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="canvas" width="500" height="300"></canvas>
<input type="button" id="undo" value="undo">
I think that you're looking for ctx.lineCap property.
+ I modified your redraw function to use a switchinstead of your confusing if statements :
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.lineCap = "round";
ctx.beginPath();
for(var i=0; i < points.length; i++) {
var pt = points[i];
switch(pt.mode){
case "begin" : ctx.moveTo(pt.x, pt.y);
case "draw" : ctx.lineTo(pt.x, pt.y);
case "end" : ctx.stroke();
}
}
}
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var points = [];
var size = 10;
var prevX = 0;
var prevY = 0;
var isCanDraw = false;
var rect = canvas.getBoundingClientRect();
$("#canvas").on("mousedown", function(e) {
isCanDraw = true;
prevX = e.clientX;
prevY = e.clientY;
points.push({
x: prevX,
y: prevY,
size: size,
mode: "begin"
});
ctx.beginPath();
ctx.arc(prevX, prevY, size/2, 0, Math.PI*2);
ctx.fill();
});
$("#canvas").on("mousemove", function(e) {
if (isCanDraw) {
stroke(e.clientX - rect.left, e.clientY - rect.top);
points.push({
x: prevX,
y: prevY,
size: size,
mode: "draw"
});
}
});
$("#canvas").on("mouseup", function(e) {
isCanDraw = false;
points.push({
x: prevX,
y: prevY,
size: size,
mode: "end"
});
});
$("#canvas").on("mouseleave", function(e) {
isCanDraw = false;
});
$("#undo").on("click", function(e) {
deleteLast();
redraw();
});
function deleteLast() {
if (points.length != 0) {
var i = points.length - 1;
while (points[i].mode != "begin") {
i--;
points.pop();
}
points.pop();
}
}
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.lineCap = "round";
ctx.beginPath();
for (var i = 0; i < points.length; i++) {
var pt = points[i];
switch (pt.mode) {
case "begin":
ctx.moveTo(pt.x, pt.y);
case "draw":
ctx.lineTo(pt.x, pt.y);
case "end":
ctx.stroke();
}
}
}
function stroke(x, y) {
ctx.lineWidth = size;
ctx.lineJoin = "round";
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(x, y);
ctx.closePath();
ctx.stroke();
prevX = x;
prevY = y;
}
// debounce our rect update func
var scrolling = false;
function scrollHandler(){
rect = canvas.getBoundingClientRect();
scrolling = false;
}
$(window).on('scroll resize', function(e){
if(!scrolling){
requestAnimationFrame(scrollHandler);
}
});
#canvas {
border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="canvas" width="500" height="300"></canvas>
<input type="button" id="undo" value="undo">
#Kaiido answers correctly that applying lineCap='round' will round the ends of your redrawn line.
Two further thoughts:
You should account for your canvas's offset position from the top-left corner of the document. Otherwise your prevX & prevY positions will be slightly off if the canvas is not on the top-left of the document.
You will have a more crisp line (less "bulgy") if you allow only the beginning and ending linecaps to be rounded and all the interim linecaps to be butted. Leave the linejoins as the default of mitered.
Here's example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var points = [];
var size = 10;
var prevX = 0;
var prevY = 0;
var isCanDraw = false;
$("#canvas").on("mousedown", function(e) {
isCanDraw = true;
prevX = e.clientX-offsetX;
prevY = e.clientY-offsetY;
points.push({x: prevX, y: prevY, size: size, mode: "begin"});
});
$("#canvas").on("mousemove", function(e) {
if(isCanDraw) {
stroke(e.clientX-offsetX, e.clientY-offsetY);
points.push({x: prevX, y: prevY, size: size, mode: "draw"});
}
});
$("#canvas").on("mouseup", function(e) {
isCanDraw = false;
points.push({x: prevX, y: prevY, size: size, mode: "end"});
});
$("#canvas").on("mouseleave", function(e) {
isCanDraw = false;
});
$("#undo").on("click", function(e) {
deleteLast();
redraw();
});
function deleteLast() {
if(points.length != 0) {
var i = points.length - 1;
while(points[i].mode !== "begin") {
i--;
points.pop();
}
points.pop();
}
}
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
var savedFillStyle=ctx.fillStyle;
ctx.fillStyle=ctx.strokeStyle;
var i=0;
while(i<points.length){
var p=points[i];
// draw "begin" as circle instead of line
ctx.beginPath();
ctx.arc(p.x,p.y,p.size/2,0,Math.PI*2);
ctx.closePath();
ctx.fill();
// draw "draw"
ctx.lineWidth=p.size;
ctx.beginPath();
ctx.moveTo(p.x,p.y);
i++;
while(i<points.length && points[i].mode!='end'){
var p=points[i];
ctx.lineTo(p.x,p.y);
i++;
}
ctx.stroke();
// draw "end" as circle instead of line
var p=points[i];
ctx.beginPath();
ctx.arc(p.x,p.y,p.size/2,0,Math.PI*2);
ctx.closePath();
ctx.fill();
i++;
}
ctx.fillStyle=savedFillStyle;
}
function stroke(x,y) {
ctx.lineWidth = size;
ctx.lineJoin = "round";
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(x, y);
ctx.closePath();
ctx.stroke();
prevX = x;
prevY = y;
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="canvas" width="500" height="300"></canvas>
<input type="button" id="undo" value="undo"> </body>

Limit values between two points on an arc?

I'm trying to adapt the code from a previous question on circular dial controls. The concept is pretty similar to this one, except I would like to define a range in which the dial cannot be selected. Consider the volume controls/dials in hardware; they often have these 'dead zones' where they can't be turned:
How can I replicate this in JavaScript? Here's the adapted code so far:
function Dial(size) {
var dial = this;
var canvas = document.querySelector('#c');
var ctx = canvas.getContext("2d");
var pi2 = Math.PI*2;
this.from = 0.75 * Math.PI;
this.to = 0.25 * Math.PI;
this.value = this.from;
var radius = size / 2 - 10;
this.draw = function() {
ctx.save();
ctx.clearRect(0,0,size,size);
ctx.translate(size/2,size/2);
ctx.beginPath();
ctx.strokeStyle = "silver";
ctx.lineWidth = 2;
ctx.arc(0, 0, radius, this.from, this.to);
ctx.stroke();
ctx.beginPath();
ctx.lineWidth = 1;
ctx.fillStyle = "green";
ctx.strokeStyle = "black";
ctx.arc(-radius*Math.sin(this.value),
-radius*Math.cos(this.value),
8, 0, 2*Math.PI);
ctx.fill();
ctx.stroke();
ctx.restore();
};
var getMousePos = function(canvas, evt) {
return {
x: event.pageX - canvas.offsetLeft,
y: event.pageY - canvas.offsetTop
};
};
var inBounds = function(pos) {
return Math.hypot(
size / 2 - radius * Math.sin(dial.value) - pos.x,
size / 2 - radius * Math.cos(dial.value) - pos.y
) <= 8;
};
canvas.addEventListener("mousemove", function(evt) {
var pos = getMousePos(canvas, evt);
if (dial.markerMoving) {
if (pos.x == size/2 && pos.y == size/2)
return;
dial.value = Math.atan2(size/2-pos.x,size/2-pos.y);
}
dial.draw();
}, false);
canvas.addEventListener("mousedown", function(evt) {
var pos = getMousePos(canvas, evt);
dial.markerMoving = inBounds(pos);
}, false);
canvas.addEventListener("mouseup", function(evt) {
dial.markerMoving = false;
}, false);
this.draw();
};
new Dial(150);
<canvas id="c"></canvas>
Bonus points if you can work out how to display a 'range' on the selection - from the starting point on the dial to the selection point.
Turns out it was pretty straightforward, using Math.abs.
function Dial(size) {
var dial = this;
var canvas = document.querySelector('#c');
var ctx = canvas.getContext("2d");
var pi2 = Math.PI*2;
this.from = 0.75 * Math.PI;
this.to = 0.25 * Math.PI;
this.value = this.from;
var radius = size / 2 - 10;
this.draw = function() {
ctx.save();
ctx.clearRect(0,0,size,size);
ctx.translate(size/2,size/2);
ctx.beginPath();
ctx.strokeStyle = "silver";
ctx.lineWidth = 2;
ctx.arc(0, 0, radius, this.from, this.to);
ctx.stroke();
ctx.beginPath();
ctx.lineWidth = 1;
ctx.fillStyle = "green";
ctx.strokeStyle = "black";
ctx.arc(-radius*Math.sin(this.value),
-radius*Math.cos(this.value),
8, 0, 2*Math.PI);
ctx.fill();
ctx.stroke();
ctx.restore();
};
var getMousePos = function(canvas, evt) {
return {
x: event.pageX - canvas.offsetLeft,
y: event.pageY - canvas.offsetTop
};
};
var inBounds = function(pos) {
return Math.hypot(
size / 2 - radius * Math.sin(dial.value) - pos.x,
size / 2 - radius * Math.cos(dial.value) - pos.y
) <= 8;
};
canvas.addEventListener("mousemove", function(evt) {
var pos = getMousePos(canvas, evt);
if (dial.markerMoving) {
if (pos.x == size/2 && pos.y == size/2) {
return;
}
var radians = Math.atan2(size/2-pos.x,size/2-pos.y);
if (Math.abs(radians) < dial.from) {
dial.value = radians;
dial.draw();
}
}
}, false);
canvas.addEventListener("mousedown", function(evt) {
var pos = getMousePos(canvas, evt);
dial.markerMoving = inBounds(pos);
}, false);
canvas.addEventListener("mouseup", function(evt) {
dial.markerMoving = false;
}, false);
this.draw();
};
new Dial(150);
<canvas id="c"></canvas>

Categories

Resources