Related
First off i'm new to javascript and still learning its basics, i'm trying to determine in which box i clicked(canvas).
My boxes are a list of dictionaries that look like this if we use console.log to visualize them, let's call that list labels:
[
{"id":"1","image":"1-0.png","name":"","xMax":"4802","xMin":"4770","yMax":"156","yMin":"141"},
{"id":"2","image":"1-0.png","name":"","xMax":"4895","xMin":"4810","yMax":"157","yMin":"141"},
{"id":"3","image":"1-0.png","name":"","xMax":"4923","xMin":"4903","yMax":"156","yMin":"145"},
{"id":"4","image":"1-0.png","name":"","xMax":"4956","xMin":"4931","yMax":"156","yMin":"145"}
]
Here we can see we have 4 rectangles and their coordinates.
The function i used to get mouse clicks is :
canvas.addEventListener("contextmenu", getPosition, false);
function getPosition(event) {
event.preventDefault();
var x = event.x;
var y = event.y;
var canvas = document.getElementById("canvas");
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
console.log("x:" + x + " y:" + y);
}
The part where i'm struggling is to find out if where i clicked are inside any of the boxes and if the click is inside one i want the id.
What i tried:
I tried adding this after the console.log in the previous code snippet:
for (i = 0,i < labels.length; i++) {
if (x>labels[i].xMin) and (x<labels[i].xMax) and (y>labels[i].yMin) and (y<labels[i].yMax) {
log.console(labels[i].id)
}
}
but it didn't work
The rects in Labels are all very far to the right, so probably you need to add the scroll position to the mouse position.
Made a working example (open the console to see the result):
https://jsfiddle.net/dgw0sxu5/
<html>
<head>
<style>
body{
background: #000;
margin: 0
}
</style>
<script>
//Some object which is used to return an id from a click
//Added a fillStyle property for testing purposes
var Labels = [
{"id":"0","image":"1-0.png","name":"","xMax":"4956","xMin":"0","yMax":"50","yMin":"0","fillStyle":"pink"},
{"id":"1","image":"1-0.png","name":"","xMax":"4802","xMin":"4770","yMax":"156","yMin":"141","fillStyle":"red"},
{"id":"2","image":"1-0.png","name":"","xMax":"4895","xMin":"4810","yMax":"157","yMin":"141","fillStyle":"blue"},
{"id":"3","image":"1-0.png","name":"","xMax":"4923","xMin":"4903","yMax":"156","yMin":"145","fillStyle":"limegreen"},
{"id":"4","image":"1-0.png","name":"","xMax":"4956","xMin":"4931","yMax":"156","yMin":"145","fillStyle":"aqua"}
];
//Initialisiing for the testcase
window.onload = function(){
//The canvas used for click events
var tCanvas = document.body.appendChild(document.createElement('canvas'));
tCanvas.width = 4956; //Highest xMax value from labels
tCanvas.height = 157; //Highest yMax value from labels
//The graphical object
var tCTX = tCanvas.getContext('2d');
//Drawing the background
tCTX.fillStyle = '#fff';
tCTX.fillRect(0, 0, tCanvas.width, tCanvas.height);
//Drawing the rects for testing purposes
//The rectangles are kinda far on the right side
for(var i=0, j=Labels.length; i<j; i++){
tCTX.fillStyle = Labels[i].fillStyle;
tCTX.fillRect(+(Labels[i].xMin), +(Labels[i].yMin), +(Labels[i].xMax)-+(Labels[i].xMin), +(Labels[i].yMax)-+(Labels[i].yMin));
};
tCanvas.onclick = function(event){
var tX = event.clientX - this.offsetLeft + (document.body.scrollLeft || document.documentElement.scrollLeft), //X-Position of click in canvas
tY = event.clientY - this.offsetTop + (document.body.scrollTop || document.documentElement.scrollTop), //Y-Position of click in canvas
tR = []; //All found id at that position (can be more in theory)
//Finding the Labels fitting the click to their bounds
for(var i=0, j=Labels.length; i<j; i++){
if(tX >= +(Labels[i].xMin) && tX <= +(Labels[i].xMax) && tY >= +(Labels[i].yMin) && +(tY) <= +(Labels[i].yMax)){
tR.push(Labels[i].id)
}
};
console.log(
'Following ids found at the position #x. #y.: '
.replace('#x.', tX)
.replace('#y.', tY),
tR.join(', ')
)
}
}
</script>
</head>
<body></body>
</html>
First of all: what exactly did not work?
var canvas = document.getElementById("canvas"); should be outside of your function to save performance at a second call.
And getting coordinates is not complicated, but complex.
There is a great resource on how to get the right ones: http://javascript.info/coordinates
Be sure about the offset measured relative to the parent element (offsetParent and also your offsetLeft), document upper left (pageX) or viewport upper left (clientX).
Your logic seems to be correct, you just need to fix the syntax.
for (i = 0; i < labels.length; i++) {
if ((x>labels[i].xMin) && (x<labels[i].xMax) && (y>labels[i].yMin) && (y<labels[i].yMax)) {
console.log(labels[i].id)
}
}
Here is a complete example:
labels = [
{"id":"1","image":"1-0.png","name":"","xMax":"4802","xMin":"4770","yMax":"156","yMin":"141"},
{"id":"2","image":"1-0.png","name":"","xMax":"4895","xMin":"4810","yMax":"157","yMin":"141"},
{"id":"3","image":"1-0.png","name":"","xMax":"4923","xMin":"4903","yMax":"156","yMin":"145"},
{"id":"4","image":"1-0.png","name":"","xMax":"4956","xMin":"4931","yMax":"156","yMin":"145"}
]
var canvas = document.getElementById("canvas");
canvas.addEventListener("contextmenu", getPosition, false);
function getPosition(event) {
event.preventDefault();
var x = event.clientX;
var y = event.clientY;
var label = labels.find(function(label){
return (x>label.xMin) && (x<label.xMax) && (y>label.yMin) && (y<label.yMax)
});
if(label){
console.log("clicked label", label.id);
}else{
console.log("no label was clicked");
}
}
Below is a script which defines two functions that draw 4 rectangular buttons and 1 circular button respectively. I am trying to implement specific Hover and Click functionality into the buttons (as described in the script alerts) but I am at a bit of a loss as to how to do this. I tried calling the makeInteractiveButton() functions on each click but this caused a lot of odd overlap and lag. I want the script to do the following:
If the circular button is hovered, I would like it's fillColour to change and if it is clicked I would like it to change again to the colours described in the code (#FFC77E for hover, #FFDDB0 for clicked). This should only happen for the duration of the hover or click.
HTML:
<html lang="en">
<body>
<canvas id="game" width = "750" height = "500"></canvas>
<script type='text/javascript' src='stack.js'></script>
</body>
</html>
JavaScript:
var c=document.getElementById('game'),
canvasX=c.offsetLeft,
canvasY=c.offsetTop,
ctx=c.getContext('2d')
elements = [];
c.style.background = 'grey';
function makeInteractiveButton(x, strokeColor, fillColor) {
ctx.strokeStyle=strokeColor;
ctx.fillStyle=fillColor;
ctx.beginPath();
ctx.lineWidth=6;
ctx.arc(x, 475, 20, 0, 2*Math.PI);
ctx.closePath();
ctx.stroke();
ctx.fill();
elements.push({
arcX: x,
arcY: 475,
arcRadius: 20
});
}
b1 = makeInteractiveButton(235, '#FFFCF8', '#FFB85D');
c.addEventListener('mousemove', function(event) {
x=event.pageX-canvasX; // cursor location
y=event.pageY-canvasY;
elements.forEach(function(element) {
if (x > element.left && x < element.left + element.width &&
y > element.top && y < element.top + element.height) { // if cursor in rect
alert('Rectangle should undergo 5 degree rotation and 105% scale');
}
else if (Math.pow(x-element.arcX, 2) + Math.pow(y-element.arcY, 2) <
Math.pow(element.arcRadius, 2)) { // if cursor in circle
alert('Set b1 fillColour to #FFC77E.');
}
});
}, false);
c.addEventListener('click', function(event) {
x=event.pageX-canvasX; // cursor location
y=event.pageY-canvasY;
elements.forEach(function(element) {
if (x > element.left && x < element.left + element.width &&
y > element.top && y < element.top + element.height) { // if rect clicked
alert('Move all cards to centre simultaneously.');
}
else if (Math.pow(x-element.arcX, 2) + Math.pow(y-element.arcY, 2) <
Math.pow(element.arcRadius, 2)) { // if circle clicked
alert('Set b1 fillColour to #FFDDB0.');
}
});
}, false);
One way is keep all element data and write a hitTest(x,y) function but when you have a lot of complex shapes its better to use a secondary canvas to render element with their ID instead of their color in it and the color of x,y in second canvas is ID of hitted element, I should mention that the second canvas is'nt visible and its just a gelper for get the hitted element.
Github Sample:
https://siamandmaroufi.github.io/CanvasElement/
Simple implementation of hitTest for Rectangles :
var Rectangle = function(id,x,y,width,height,color){
this.id = id;
this.x=x;
this.y=y;
this.width = width;
this.height = height;
this.color = color || '#7cf';
this.selected = false;
}
Rectangle.prototype.draw = function(ctx){
ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.width,this.height);
if(this.selected){
ctx.strokeStyle='red';
ctx.setLineDash([5,5]);
ctx.lineWidth = 5;
ctx.strokeRect(this.x,this.y,this.width,this.height);
}
}
Rectangle.prototype.hitTest=function(x,y){
return (x >= this.x) && (x <= (this.width+this.x)) &&
(y >= this.y) && (y <= (this.height+this.y));
}
var Paint = function(el) {
this.element = el;
this.shapes = [];
}
Paint.prototype.addShape = function(shape){
this.shapes.push(shape);
}
Paint.prototype.render = function(){
//clear the canvas
this.element.width = this.element.width;
var ctx = this.element.getContext('2d');
for(var i=0;i<this.shapes.length;i++){
this.shapes[i].draw(ctx);
}
}
Paint.prototype.setSelected = function(shape){
for(var i=0;i<this.shapes.length;i++){
this.shapes[i].selected = this.shapes[i]==shape;
}
this.render();
}
Paint.prototype.select = function(x,y){
for(var i=this.shapes.length-1;i>=0;i--){
if(this.shapes[i].hitTest(x,y)){
return this.shapes[i];
}
}
return null;
}
var el = document.getElementById('panel');
var paint = new Paint(el);
var rectA = new Rectangle('A',10,10,150,90,'yellow');
var rectB = new Rectangle('B',150,90,140,100,'green');
var rectC = new Rectangle('C',70,85,200,70,'rgba(0,0,0,.5)');
paint.addShape(rectA);
paint.addShape(rectB);
paint.addShape(rectC);
paint.render();
function panel_mouseUp(evt){
var p = document.getElementById('panel');
var x = evt.x - p.offsetLeft;
var y = evt.y - p.offsetTop;
var shape = paint.select(x,y);
if(shape){
alert(shape.id);
}
//console.log('selected shape :',shape);
}
function panel_mouseMove(evt){
var p = document.getElementById('panel');
var x = evt.x - p.offsetLeft;
var y = evt.y - p.offsetTop;
var shape = paint.select(x,y);
paint.setSelected(shape);
}
el.addEventListener('mouseup',panel_mouseUp);
el.addEventListener('mousemove',panel_mouseMove);
body {background:#e6e6e6;}
#panel {
border:solid thin #ccc;
background:#fff;
margin:0 auto;
display:block;
}
<canvas id="panel" width="400px" height="200px" >
</canvas>
just click or move over the shapes
I am creating an svg object with javascript, drawing a basic Sierpinski triangle, and then setting the svg object as a svg-pan-zoom. When zooming past a threshold, I try to re-draw the next level of triangles, which I can see on screen, but they do not react to zooming or panning.
I am currently trying to re-apply the svg-pan-zoom to the object after drawing the next level of triangles, but that does not seem to work.
The HTML is basically an empty body.
The JS code in question:
var width = 300;
var height = 300;
var length;
var maxDepth = 5;
var depth = 0;
var svg;
var div;
//2D array of triangles, where first index is their recursive depth at an offset
var triangles;
var zoomCount = 0;
$(document).ready(function () {
//init();
var ns = 'http://www.w3.org/2000/svg'
div = document.getElementById('drawing')
svg = document.createElementNS(ns, 'svg')
svg.setAttributeNS(null, 'id', 'svg-id')
svg.setAttributeNS(null, 'width', '100%')
svg.setAttributeNS(null, 'height', '100%')
div.appendChild(svg)
/*var rect = document.createElementNS(ns, 'rect')
rect.setAttributeNS(null, 'width', 100)
rect.setAttributeNS(null, 'height', 100)
rect.setAttributeNS(null, 'fill', '#f06')
svg.appendChild(rect)*/
init();
enableZoomPan();
});
function init() {
triangles = create2DArray(5);
//Calculate triangle line length
length = height/Math.sin(60*Math.PI/180) //Parameter conversion to radians
t = new Triangle(new Point(0, height), new Point(width, height), new Point(width/2, 0));
sketchTriangle(t);
//Recursively draw children triangles
drawSubTriangles(t, true);
attachMouseWheelListener();
}
function enableZoomPan() {
//Enable zoom/pan
var test = svgPanZoom('#svg-id', {
zoomEnabled: true,
controlIconsEnabled: false,
fit: true,
center: true,
minZoom: 0
});
}
function attachMouseWheelListener() {
if (div.addEventListener)
{
// IE9, Chrome, Safari, Opera
div.addEventListener("mousewheel", MouseWheelHandler, false);
// Firefox
div.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
// IE 6/7/8
else
{
div.attachEvent("onmousewheel", MouseWheelHandler);
}
function MouseWheelHandler(e)
{
// cross-browser wheel delta
var e = window.event || e; // old IE support
//Delta +1 -> scrolled up
//Delta -1 -> scrolled down
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
console.log(delta);
zoomCount = zoomCount + delta;
if(zoomCount==15) {
for(var i = 0; i < triangles[0].length; i++) {
drawSubTriangles(triangles[0][i], false);
}
enableZoomPan();
}
return false;
}
}
function drawLine(p1, p2) {
var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', p1.x);
line.setAttribute('y1', p1.y);
line.setAttribute('x2', p2.x);
line.setAttribute('y2', p2.y);
line.setAttribute('stroke', "black");
line.setAttribute('stroke-width', 1);
svg.appendChild(line);
}
//Recursive parameter if you want to draw recursively, or just stop after one level
function drawSubTriangles(t, recursive) {
//End condition, bounded by maximum recursion depth
if(depth == maxDepth && recursive==true) {
//Push triangle to depth collection, to track in case zooming in and redrawing
triangles[maxDepth-depth].push(t);
return;
}
depth = depth + 1;
//Sub triangle lengths are half of parent triangle
subLength = length/depth;
var midPoint1 = getCenter(t.p1, t.p2);
var midPoint2 = getCenter(t.p2, t.p3);
var midPoint3 = getCenter(t.p3, t.p1);
midTriangle = new Triangle(midPoint1, midPoint2, midPoint3);
sketchTriangle(midTriangle)
//Recursive call to continue drawing children triangles until max depth
if(recursive == true) {
drawSubTriangles(new Triangle(t.p1, midPoint1, midPoint3), true);
drawSubTriangles(new Triangle(midPoint3, midPoint2, t.p3), true);
drawSubTriangles(new Triangle(midPoint1, t.p2, midPoint2), true);
}
depth = depth -1;
}
function sketchTriangle(t) {
drawLine(t.p1, t.p2);
drawLine(t.p2, t.p3);
drawLine(t.p3, t.p1);
}
function create2DArray(rows) {
var arr = [];
for (var i=0;i<rows;i++) {
arr[i] = [];
}
return arr;
}
function getCenter(p1, p2) {
return new Point((p1.x + p2.x)/2, (p1.y + p2.y)/2);
}
function Point(x, y) {
this.x = x;
this.y = y;
}
function Triangle(p1, p2, p3) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
For some reason, svg-pan-zoom is wrapping all your SVG content inside a <g> element. Panning and zooming is then achieved by modifying a transform attribute associated with this element. So in effect, the first time you interact with the SVG, its structure changes from this:
<svg>
<line ...>
<line ...>
...
</svg>
to this:
<svg>
<g transform="matrix(1 0 0 1 0 0)">
<line ...>
<line ...>
...
</g>
</svg>
When you add more elements to the drawing, they are being appended to the root <svg> element. As a result, they aren't being transformed at all.
You can fix this easily enough. Just wrap your drawing inside a <g> element before invoking svg-pan-zoom. It will then use this element instead of adding its own. When adding to the drawing, append the new objects to this element.
Here's your code, with very minor modifications:
var width = 300;
var height = 300;
var length;
var maxDepth = 5;
var depth = 0;
var svg;
var svgg; /* Top <g> element inside svg */
var div;
//2D array of triangles, where first index is their recursive depth at an offset
var triangles;
var zoomCount = 0;
$(document).ready(function () {
//init();
var ns = 'http://www.w3.org/2000/svg'
div = document.getElementById('drawing')
svg = document.createElementNS(ns, 'svg')
svg.setAttributeNS(null, 'id', 'svg-id')
svg.setAttributeNS(null, 'width', '100%')
svg.setAttributeNS(null, 'height', '100%')
svgg = document.createElementNS(ns, 'g')
svg.appendChild(svgg)
div.appendChild(svg)
init();
enableZoomPan();
});
function init() {
triangles = create2DArray(5);
//Calculate triangle line length
length = height/Math.sin(60*Math.PI/180) //Parameter conversion to radians
t = new Triangle(new Point(0, height), new Point(width, height), new Point(width/2, 0));
sketchTriangle(t);
//Recursively draw children triangles
drawSubTriangles(t, true);
attachMouseWheelListener();
}
function enableZoomPan() {
//Enable zoom/pan
var test = svgPanZoom('#svg-id', {
zoomEnabled: true,
controlIconsEnabled: false,
fit: true,
center: true,
minZoom: 0
});
}
function attachMouseWheelListener() {
if (div.addEventListener)
{
// IE9, Chrome, Safari, Opera
div.addEventListener("mousewheel", MouseWheelHandler, false);
// Firefox
div.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
// IE 6/7/8
else
{
div.attachEvent("onmousewheel", MouseWheelHandler);
}
function MouseWheelHandler(e)
{
// cross-browser wheel delta
var e = window.event || e; // old IE support
//Delta +1 -> scrolled up
//Delta -1 -> scrolled down
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
zoomCount = zoomCount + delta;
if(zoomCount==15) {
for(var i = 0; i < triangles[0].length; i++) {
drawSubTriangles(triangles[0][i], false);
}
enableZoomPan();
}
return false;
}
}
function drawLine(p1, p2) {
var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', p1.x);
line.setAttribute('y1', p1.y);
line.setAttribute('x2', p2.x);
line.setAttribute('y2', p2.y);
line.setAttribute('stroke', "black");
line.setAttribute('stroke-width', 1);
svgg.appendChild(line);
}
//Recursive parameter if you want to draw recursively, or just stop after one level
function drawSubTriangles(t, recursive) {
//End condition, bounded by maximum recursion depth
if(depth == maxDepth && recursive==true) {
//Push triangle to depth collection, to track in case zooming in and redrawing
triangles[maxDepth-depth].push(t);
return;
}
depth = depth + 1;
//Sub triangle lengths are half of parent triangle
subLength = length/depth;
var midPoint1 = getCenter(t.p1, t.p2);
var midPoint2 = getCenter(t.p2, t.p3);
var midPoint3 = getCenter(t.p3, t.p1);
midTriangle = new Triangle(midPoint1, midPoint2, midPoint3);
sketchTriangle(midTriangle)
//Recursive call to continue drawing children triangles until max depth
if(recursive == true) {
drawSubTriangles(new Triangle(t.p1, midPoint1, midPoint3), true);
drawSubTriangles(new Triangle(midPoint3, midPoint2, t.p3), true);
drawSubTriangles(new Triangle(midPoint1, t.p2, midPoint2), true);
}
depth = depth -1;
}
function sketchTriangle(t) {
drawLine(t.p1, t.p2);
drawLine(t.p2, t.p3);
drawLine(t.p3, t.p1);
}
function create2DArray(rows) {
var arr = [];
for (var i=0;i<rows;i++) {
arr[i] = [];
}
return arr;
}
function getCenter(p1, p2) {
return new Point((p1.x + p2.x)/2, (p1.y + p2.y)/2);
}
function Point(x, y) {
this.x = x;
this.y = y;
}
function Triangle(p1, p2, p3) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ariutta.github.io/svg-pan-zoom/dist/svg-pan-zoom.js"></script>
<div id="drawing"></div>
Note: One thing I don't understand is why svg-pan-zoom doesn't just modify the SVG viewBox attribute. Then it wouldn't have to modify the document structure at all.
I implemented a freehand drawing of a path using native JS. But as expected path edges are little aggressive and not smooth. So I have an option of using simplifyJS to simplify points and then redraw path. But like here, instead of smoothening after drawing, I am trying to find simplified edges while drawing
Here is my code:
var x0, y0;
var dragstart = function(event) {
var that = this;
var pos = coordinates(event);
x0 = pos.x;
y0 = pos.y;
that.points = [];
};
var dragging = function(event) {
var that = this;
var xy = coordinates(event);
var points = that.points;
var x1 = xy.x, y1 = xy.y, dx = x1 - x0, dy = y1 - y0;
if (dx * dx + dy * dy > 100) {
xy = {
x: x0 = x1,
y: y0 = y1
};
} else {
xy = {
x: x1,
y: y1
};
}
points.push(xy);
};
But it is not working as in the link added above. Still edges are not good. Please help.
The following code snippet makes the curve smoother by calculating the average of the last mouse positions. The level of smoothing depends on the size of the buffer in which these values are kept. You can experiment with the different buffer sizes offered in the dropdown list. The behavior with a 12 point buffer is somewhat similar to the Mike Bostock's code snippet that you refer to in the question.
More sophisticated techniques could be implemented to get the smoothed point from the positions stored in the buffer (weighted average, linear regression, cubic spline smoothing, etc.) but this simple average method may be sufficiently accurate for your needs.
var strokeWidth = 2;
var bufferSize;
var svgElement = document.getElementById("svgElement");
var rect = svgElement.getBoundingClientRect();
var path = null;
var strPath;
var buffer = []; // Contains the last positions of the mouse cursor
svgElement.addEventListener("mousedown", function (e) {
bufferSize = document.getElementById("cmbBufferSize").value;
path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute("fill", "none");
path.setAttribute("stroke", "#000");
path.setAttribute("stroke-width", strokeWidth);
buffer = [];
var pt = getMousePosition(e);
appendToBuffer(pt);
strPath = "M" + pt.x + " " + pt.y;
path.setAttribute("d", strPath);
svgElement.appendChild(path);
});
svgElement.addEventListener("mousemove", function (e) {
if (path) {
appendToBuffer(getMousePosition(e));
updateSvgPath();
}
});
svgElement.addEventListener("mouseup", function () {
if (path) {
path = null;
}
});
var getMousePosition = function (e) {
return {
x: e.pageX - rect.left,
y: e.pageY - rect.top
}
};
var appendToBuffer = function (pt) {
buffer.push(pt);
while (buffer.length > bufferSize) {
buffer.shift();
}
};
// Calculate the average point, starting at offset in the buffer
var getAveragePoint = function (offset) {
var len = buffer.length;
if (len % 2 === 1 || len >= bufferSize) {
var totalX = 0;
var totalY = 0;
var pt, i;
var count = 0;
for (i = offset; i < len; i++) {
count++;
pt = buffer[i];
totalX += pt.x;
totalY += pt.y;
}
return {
x: totalX / count,
y: totalY / count
}
}
return null;
};
var updateSvgPath = function () {
var pt = getAveragePoint(0);
if (pt) {
// Get the smoothed part of the path that will not change
strPath += " L" + pt.x + " " + pt.y;
// Get the last part of the path (close to the current mouse position)
// This part will change if the mouse moves again
var tmpPath = "";
for (var offset = 2; offset < buffer.length; offset += 2) {
pt = getAveragePoint(offset);
tmpPath += " L" + pt.x + " " + pt.y;
}
// Set the complete current path coordinates
path.setAttribute("d", strPath + tmpPath);
}
};
html, body
{
padding: 0px;
margin: 0px;
}
#svgElement
{
border: 1px solid;
margin-top: 4px;
margin-left: 4px;
cursor: default;
}
#divSmoothingFactor
{
position: absolute;
left: 14px;
top: 12px;
}
<div id="divSmoothingFactor">
<label for="cmbBufferSize">Buffer size:</label>
<select id="cmbBufferSize">
<option value="1">1 - No smoothing</option>
<option value="4">4 - Sharp curves</option>
<option value="8" selected="selected">8 - Smooth curves</option>
<option value="12">12 - Very smooth curves</option>
<option value="16">16 - Super smooth curves</option>
<option value="20">20 - Hyper smooth curves</option>
</select>
</div>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="svgElement" x="0px" y="0px" width="600px" height="400px" viewBox="0 0 600 400" enable-background="new 0 0 600 400" xml:space="preserve">
Quadtratic Bézier polyline smoothing
#ConnorsFan solution works great and is probably providing a better rendering performance and more responsive drawing experience.
In case you need a more compact svg output (in terms of markup size) quadratic smoothing might be interesting.
E.g. if you need to export the drawings in an efficient way.
Simplified example: polyline smoothing
Green dots show the original polyline coordinates (in x/y pairs).
Purple points represent interpolated middle coordinates – simply calculated like so:
[(x1+x2)/2, (y1+y2)/2].
The original coordinates (highlighted green) become quadratic bézier control points
whereas the interpolated middle points will be the end points.
let points = [{
x: 0,
y: 10
},
{
x: 10,
y: 20
},
{
x: 20,
y: 10
},
{
x: 30,
y: 20
},
{
x: 40,
y: 10
}
];
path.setAttribute("d", smoothQuadratic(points));
function smoothQuadratic(points) {
// set M/starting point
let [Mx, My] = [points[0].x, points[0].y];
let d = `M ${Mx} ${My}`;
renderPoint(svg, [Mx, My], "green", "1");
// split 1st line segment
let [x1, y1] = [points[1].x, points[1].y];
let [xM, yM] = [(Mx + x1) / 2, (My + y1) / 2];
d += `L ${xM} ${yM}`;
renderPoint(svg, [xM, yM], "purple", "1");
for (let i = 1; i < points.length; i += 1) {
let [x, y] = [points[i].x, points[i].y];
// calculate mid point between current and next coordinate
let [xN, yN] = points[i + 1] ? [points[i + 1].x, points[i + 1].y] : [x, y];
let [xM, yM] = [(x + xN) / 2, (y + yN) / 2];
// add quadratic curve:
d += `Q${x} ${y} ${xM} ${yM}`;
renderPoint(svg, [xM, yM], "purple", "1");
renderPoint(svg, [x, y], "green", "1");
}
return d;
}
pathRel.setAttribute("d", smoothQuadraticRelative(points));
function smoothQuadraticRelative(points, skip = 0, decimals = 3) {
let pointsL = points.length;
let even = pointsL - skip - (1 % 2) === 0;
// set M/starting point
let type = "M";
let values = [points[0].x, points[0].y];
let [Mx, My] = values.map((val) => {
return +val.toFixed(decimals);
});
let dRel = `${type}${Mx} ${My}`;
// offsets for relative commands
let xO = Mx;
let yO = My;
// split 1st line segment
let [x1, y1] = [points[1].x, points[1].y];
let [xM, yM] = [(Mx + x1) / 2, (My + y1) / 2];
let [xMR, yMR] = [xM - xO, yM - yO].map((val) => {
return +val.toFixed(decimals);
});
dRel += `l${xMR} ${yMR}`;
xO += xMR;
yO += yMR;
for (let i = 1; i < points.length; i += 1 + skip) {
// control point
let [x, y] = [points[i].x, points[i].y];
let [xR, yR] = [x - xO, y - yO];
// next point
let [xN, yN] = points[i + 1 + skip] ?
[points[i + 1 + skip].x, points[i + 1 + skip].y] :
[points[pointsL - 1].x, points[pointsL - 1].y];
let [xNR, yNR] = [xN - xO, yN - yO];
// mid point
let [xM, yM] = [(x + xN) / 2, (y + yN) / 2];
let [xMR, yMR] = [(xR + xNR) / 2, (yR + yNR) / 2];
type = "q";
values = [xR, yR, xMR, yMR];
// switch to t command
if (i > 1) {
type = "t";
values = [xMR, yMR];
}
dRel += `${type}${values
.map((val) => {
return +val.toFixed(decimals);
})
.join(" ")} `;
xO += xMR;
yO += yMR;
}
// add last line if odd number of segments
if (!even) {
values = [points[pointsL - 1].x - xO, points[pointsL - 1].y - yO];
dRel += `l${values
.map((val) => {
return +val.toFixed(decimals);
})
.join(" ")}`;
}
return dRel;
}
function renderPoint(svg, coords, fill = "red", r = "2") {
let marker =
'<circle cx="' +
coords[0] +
'" cy="' +
coords[1] +
'" r="' +
r +
'" fill="' +
fill +
'" ><title>' +
coords.join(", ") +
"</title></circle>";
svg.insertAdjacentHTML("beforeend", marker);
}
svg {
border: 1px solid #ccc;
width: 45vw;
overflow: visible;
margin-right: 1vw;
}
path {
fill: none;
stroke-linecap: round;
stroke-linejoin: round;
stroke-opacity: 0.5;
}
<svg id="svg" viewBox="0 0 40 30">
<path d="M 0 10 L 10 20 20 10 L 30 20 40 10" fill="none" stroke="#999" stroke-width="1"></path>
<path id="path" d="" fill="none" stroke="red" stroke-width="1" />
</svg>
<svg id="svg2" viewBox="0 0 40 30">
<path d="M 0 10 L 10 20 20 10 L 30 20 40 10" fill="none" stroke="#999" stroke-width="1"></path>
<path id="pathRel" d="" fill="none" stroke="red" stroke-width="1" />
</svg>
Example: Svg draw Pad
const svg = document.getElementById("svg");
const svgns = "http://www.w3.org/2000/svg";
let strokeWidth = 0.25;
// rounding and smoothing
let decimals = 2;
let getNthMouseCoord = 1;
let smooth = 2;
// init
let isDrawing = false;
var points = [];
let path = "";
let pointCount = 0;
const drawStart = (e) => {
pointCount = 0;
isDrawing = true;
// create new path
path = document.createElementNS(svgns, "path");
svg.appendChild(path);
};
const draw = (e) => {
if (isDrawing) {
pointCount++;
if (getNthMouseCoord && pointCount % getNthMouseCoord === 0) {
let point = getMouseOrTouchPos(e);
// save to point array
points.push(point);
}
if (points.length > 1) {
let d = smoothQuadratic(points, smooth, decimals);
path.setAttribute("d", d);
}
}
};
const drawEnd = (e) => {
isDrawing = false;
points = [];
// just illustrating the ouput
svgMarkup.value = svg.outerHTML;
};
// start drawing: create new path;
svg.addEventListener("mousedown", drawStart);
svg.addEventListener("touchstart", drawStart);
svg.addEventListener("mousemove", draw);
svg.addEventListener("touchmove", draw);
// stop drawing, reset point array for next line
svg.addEventListener("mouseup", drawEnd);
svg.addEventListener("touchend", drawEnd);
svg.addEventListener("touchcancel", drawEnd);
function smoothQuadratic(points, skip = 0, decimals = 3) {
let pointsL = points.length;
let even = pointsL - skip - (1 % 2) === 0;
// set M/starting point
let type = "M";
let values = [points[0].x, points[0].y];
let [Mx, My] = values.map((val) => {
return +val.toFixed(decimals);
});
let dRel = `${type}${Mx} ${My}`;
// offsets for relative commands
let xO = Mx;
let yO = My;
// split 1st line segment
let [x1, y1] = [points[1].x, points[1].y];
let [xM, yM] = [(Mx + x1) / 2, (My + y1) / 2];
let [xMR, yMR] = [xM - xO, yM - yO].map((val) => {
return +val.toFixed(decimals);
});
dRel += `l${xMR} ${yMR}`;
xO += xMR;
yO += yMR;
for (let i = 1; i < points.length; i += 1 + skip) {
// control point
let [x, y] = [points[i].x, points[i].y];
let [xR, yR] = [x - xO, y - yO];
// next point
let [xN, yN] = points[i + 1 + skip] ?
[points[i + 1 + skip].x, points[i + 1 + skip].y] :
[points[pointsL - 1].x, points[pointsL - 1].y];
let [xNR, yNR] = [xN - xO, yN - yO];
// mid point
let [xM, yM] = [(x + xN) / 2, (y + yN) / 2];
let [xMR, yMR] = [(xR + xNR) / 2, (yR + yNR) / 2];
type = "q";
values = [xR, yR, xMR, yMR];
// switch to t command
if (i > 1) {
type = "t";
values = [xMR, yMR];
}
dRel += `${type}${values
.map((val) => {
return +val.toFixed(decimals);
})
.join(" ")} `;
xO += xMR;
yO += yMR;
}
// add last line if odd number of segments
if (!even) {
values = [points[pointsL - 1].x - xO, points[pointsL - 1].y - yO];
dRel += `l${values
.map((val) => {
return +val.toFixed(decimals);
})
.join(" ")}`;
}
return dRel;
}
/**
* based on:
* #Daniel Lavedonio de Lima
* https://stackoverflow.com/a/61732450/3355076
*/
function getMouseOrTouchPos(e) {
let x, y;
// touch cooordinates
if (
e.type == "touchstart" ||
e.type == "touchmove" ||
e.type == "touchend" ||
e.type == "touchcancel"
) {
let evt = typeof e.originalEvent === "undefined" ? e : e.originalEvent;
let touch = evt.touches[0] || evt.changedTouches[0];
x = touch.pageX;
y = touch.pageY;
} else if (
e.type == "mousedown" ||
e.type == "mouseup" ||
e.type == "mousemove" ||
e.type == "mouseover" ||
e.type == "mouseout" ||
e.type == "mouseenter" ||
e.type == "mouseleave"
) {
x = e.clientX;
y = e.clientY;
}
// get svg user space coordinates
let point = svg.createSVGPoint();
point.x = x;
point.y = y;
let ctm = svg.getScreenCTM().inverse();
point = point.matrixTransform(ctm);
return point;
}
body {
margin: 0;
font-family: sans-serif;
padding: 1em;
}
* {
box-sizing: border-box;
}
svg {
width: 100%;
max-height: 75vh;
overflow: visible;
}
textarea {
width: 100%;
min-height: 50vh;
resize: none;
}
.border {
border: 1px solid #ccc;
}
path {
fill: none;
stroke: #000;
stroke-linecap: round;
stroke-linejoin: round;
}
input[type="number"] {
width: 3em;
}
input[type="number"]::-webkit-inner-spin-button {
opacity: 1;
}
#media (min-width: 720px) {
svg {
width: 75%;
}
textarea {
width: 25%;
}
.flex {
display: flex;
gap: 1em;
}
.flex * {
flex: 1 0 auto;
}
}
<h2>Draw quadratic bezier (relative commands)</h2>
<p><button type="button" id="clear" onclick="clearDrawing()">Clear</button>
<label>Get nth Mouse position</label><input type="number" id="nthMouseCoord" value="1" min="0" oninput="changeVal()">
<label>Smooth</label><input type="number" id="simplifyDrawing" min="0" value="2" oninput="changeVal()">
</p>
<div class="flex">
<svg class="border" id="svg" viewBox="0 0 200 100">
</svg>
<textarea class="border" id="svgMarkup"></textarea>
</div>
<script>
function changeVal() {
getNthMouseCoord = +nthMouseCoord.value + 1;
simplify = +simplifyDrawing.value;;
}
function clearDrawing() {
let paths = svg.querySelectorAll('path');
paths.forEach(path => {
path.remove();
})
}
</script>
How it works
save mouse/cursor positions in a point array via event listeners
Event Listeners (including touch events):
function getMouseOrTouchPos(e) {
let x, y;
// touch cooordinates
if (e.type == "touchstart" || e.type == "touchmove" || e.type == "touchend" || e.type == "touchcancel"
) {
let evt = typeof e.originalEvent === "undefined" ? e : e.originalEvent;
let touch = evt.touches[0] || evt.changedTouches[0];
x = touch.pageX;
y = touch.pageY;
} else if ( e.type == "mousedown" || e.type == "mouseup" || e.type == "mousemove" || e.type == "mouseover" || e.type == "mouseout" || e.type == "mouseenter" || e.type == "mouseleave") {
x = e.clientX;
y = e.clientY;
}
// get svg user space coordinates
let point = svg.createSVGPoint();
point.x = x;
point.y = y;
let ctm = svg.getScreenCTM().inverse();
point = point.matrixTransform(ctm);
return point;
}
It's crucial to translate HTML DOM cursor coordinates to SVG DOM user units unless your svg viewport corresponds to the HTML placement 1:1.
let ctm = svg.getScreenCTM().inverse();
point = point.matrixTransform(ctm);
optional: skip cursor points and use every nth point respectively (pre processing – aimed at reducing the total amount of cursor coordinates)
optional: similar to the previous measure: smooth by skipping polyine segments – the curve control point calculation will skip succeeding mid and control points (post processing – calculate curves based on retrieved point array but skip points).
Q to T simplification: Since we are splitting the polyline coordinates evenly we can simplify the path d output by using the quadratic shorthand command T repeating the previous tangents.
Converting to relative commands and rounding
Based on x/y offsets globally incremented by the previous command's end point.
Depending on your layout sizes you need to tweak smoothing values.
For a "micro smoothing" you should also include these css properties:
path {
fill: none;
stroke: #000;
stroke-linecap: round;
stroke-linejoin: round;
}
Further reading
Change T command to Q command in SVG
There are already some implementations for this on github e.g. https://github.com/epistemex/cardinal-spline-js
You dont have to change anything on your input for that and can only change the draw function, that the line between the points is smooth. With that the points dont slip a bit during the simplification.
I used interact.js library to write this piece of code which works absolutely fine standalone on chrome, firefox and w3schools "Try it Yourself" (doesn't work on Edge and IE for some reason). The problem is that when I call a template.phtml with this code inside from the layout.xml, the magento renders it only once, thus the user is not allowed to resize the cubes.
<!-- CSS -->
<style type="text/css">
svg {
width: 100%;
height: 300px;
background-color: #CDC9C9;
-ms-touch-action: none;
touch-action: none;
}
.edit-rectangle {
fill: black;
stroke: #fff;
}
body { margin: 0; }
</style>
<!-- Content -->
<br>
<svg>
</svg>
<br>
<button onclick="location.href = 'square';" id="previousbutton">Go back</button>
<button onclick="location.href = 'squaresection';" style="float:right" id="nextButton">Proceed to next step</button>
<br>
<br>
<script type="text/javascript" src="interact.js">
</script>
<!-- JavaScript -->
<script type="text/javascript">
var svgCanvas = document.querySelector('svg'),
svgNS = 'http://www.w3.org/2000/svg',
rectangles = [];
labels = [];
rectNumb = 5;
function Rectangle (x, y, w, h, svgCanvas) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.stroke = 0;
this.el = document.createElementNS(svgNS, 'rect');
this.el.setAttribute('data-index', rectangles.length);
this.el.setAttribute('class', 'edit-rectangle');
rectangles.push(this);
this.draw();
svgCanvas.appendChild(this.el);
}
function Label (x, y, text, svgCanvas){
this.x = x;
this.y = y;
this.text = text;
this.el = document.createElementNS(svgNS, 'text');
labels.push(this);
this.draw();
svgCanvas.appendChild(this.el);
}
Label.prototype.draw = function () {
this.el.setAttribute('x', this.x);
this.el.setAttribute('y', this.y);
this.el.setAttribute('font-family', "Verdana");
this.el.setAttribute('font-size', 14);
this.el.setAttribute('fill', "black");
this.el.innerHTML = this.text;
}
Rectangle.prototype.draw = function () {
this.el.setAttribute('x', this.x + this.stroke / 2);
this.el.setAttribute('y', this.y + this.stroke / 2);
this.el.setAttribute('width' , this.w - this.stroke);
this.el.setAttribute('height', this.h - this.stroke);
this.el.setAttribute('stroke-width', this.stroke);
}
interact('.edit-rectangle')
// change how interact gets the
// dimensions of '.edit-rectangle' elements
.rectChecker(function (element) {
// find the Rectangle object that the element belongs to
var rectangle = rectangles[element.getAttribute('data-index')];
// return a suitable object for interact.js
return {
left : rectangle.x,
top : rectangle.y,
right : rectangle.x + rectangle.w,
bottom: rectangle.y + rectangle.h
};
})
/*
.draggable({
max: Infinity,
onmove: function (event) {
var rectangle = rectangles[event.target.getAttribute('data-index')];
rectangle.x += event.dx;
rectangle.y += event.dy;
rectangle.draw();
}
})
*/
.resizable({
onstart: function (event) {},
onmove : function (event) {
if (event.target.getAttribute('data-index') > 0)
{
// Main Rect
var rectangle = rectangles[event.target.getAttribute('data-index')];
var rectangle2 = rectangles[event.target.getAttribute('data-index') - 1];
if (rectangle.w - event.dx > 10 && rectangle2.w + event.dx > 10){
rectangle.x += event.dx;
rectangle.w = rectangle.w - event.dx;
rectangle2.w = rectangle2.w + event.dx;
}
rectangle.draw();
rectangle2.draw();
var label = labels[event.target.getAttribute('data-index')];
var label2 = labels[event.target.getAttribute('data-index') - 1];
label.text = rectangle.w + " mm";
label2.text = rectangle2.w + " mm";
label.x = rectangle.x + rectangle.w / 4;
label2.x = rectangle2.x + rectangle2.w / 4;
label.draw();
label2.draw();
}
},
onend : function (event) {},
edges: {
top : false, // Disable resizing from top edge.
left : true,
bottom: false,
right : false // Enable resizing on right edge
},
inertia: false,
// Width and height can be adjusted independently. When `true`, width and
// height are adjusted at a 1:1 ratio.
square: false,
// Width and height can be adjusted independently. When `true`, width and
// height maintain the aspect ratio they had when resizing started.
preserveAspectRatio: false,
// a value of 'none' will limit the resize rect to a minimum of 0x0
// 'negate' will allow the rect to have negative width/height
// 'reposition' will keep the width/height positive by swapping
// the top and bottom edges and/or swapping the left and right edges
invert: 'reposition',
// limit multiple resizes.
// See the explanation in the #Interactable.draggable example
max: Infinity,
maxPerElement: 3,
});
interact.maxInteractions(Infinity);
var positionX = 50,
positionY = 80,
width = 80,
height = 80;
for (var i = 0; i < rectNumb; i++) {
positionX = 50 + 82 * i;
new Rectangle(positionX, positionY, width, height, svgCanvas);
}
for (var i = 0; i < rectNumb; i++) {
positionX = 50 + 82 * i;
new Label(positionX + width/4, positionY + height + 20, width +" mm", svgCanvas);
}
</script>
Any suggestions of what I could do to implement this code into magento would be much appreciated.
Magento did not render the code only once. The problem was that canvas event listener always assumed that pointer coordinates were wrong. Since canvas is the first element of the page(because it is the first element in that .phtml file), event listener assumed it will be displayed at the top, but that was not the case because of the way magento page rendering works.
This issue was resolved simply by measuring the height of content above canvas and just mathematically subtracting that from pointers position before passing it to event listener.
The problem with this solution is that it works only for single page or with multiple pages that have the same height of content above canvas(=>same design). If anyone knows a way in which person would not need to "recalculate" the height for every single page that has different design, sharing knowledge would be much appreciated.