PixiJs mask filter with background image - pixi.js

How can I create effect like on this site (work links)
https://monopo.london/work/
I was trying implement this example, but can't change black background with another image.
https://pixijs.io/examples/#/masks/filter.js
Please, HELP!
const app = new PIXI.Application();
document.body.appendChild(app.view);
// Inner radius of the circle
const radius = 100;
// The blur amount
const blurSize = 12;
app.loader.add('grass', 'https://images.prismic.io/monopolondon/abb53b73-caae-41d2-9031-f889aa27780d_onefinestay_thumb.jpeg?auto=compress,format&rect=0,0,1200,1436&w=600&h=718');
app.loader.load(setup);
function setup(loader, resources) {
const background = new PIXI.Sprite(resources.grass.texture);
app.stage.addChild(background);
background.width = app.screen.width;
background.height = app.screen.height;
const circle = new PIXI.Graphics()
.beginFill(0xFF0000)
.drawCircle(radius + blurSize, radius + blurSize, radius)
.endFill();
circle.filters = [new PIXI.filters.BlurFilter(blurSize)];
const bounds = new PIXI.Rectangle(0, 0, (radius + blurSize) * 2, (radius + blurSize) * 2);
const texture = app.renderer.generateTexture(circle, PIXI.SCALE_MODES.NEAREST, 1, bounds);
const focus = new PIXI.Sprite(texture);
console.log(texture);
app.stage.addChild(focus);
background.mask = focus;
app.stage.interactive = true;
app.stage.on('mousemove', pointerMove);
function pointerMove(event) {
focus.position.x = event.data.global.x - focus.width / 2;
focus.position.y = event.data.global.y - focus.height / 2;
}
}

Try simply adding some other Sprite to stage - before grass is added - like this:
look at usage of some_bg
const app = new PIXI.Application();
document.body.appendChild(app.view);
// Inner radius of the circle
const radius = 100;
// The blur amount
const blurSize = 32;
app.loader.add('grass', 'examples/assets/bg_grass.jpg');
app.loader.add('some_bg', 'examples/assets/bg_plane.jpg');
app.loader.load(setup);
function setup(loader, resources) {
const some_bg = new PIXI.Sprite(resources.some_bg.texture);
some_bg.width = app.screen.width;
some_bg.height = app.screen.height;
app.stage.addChild(some_bg);
console.log(some_bg);
const background = new PIXI.Sprite(resources.grass.texture);
app.stage.addChild(background);
background.width = app.screen.width;
background.height = app.screen.height;
const circle = new PIXI.Graphics()
.beginFill(0xFFFFFF)
.drawCircle(radius + blurSize, radius + blurSize, radius)
.endFill();
circle.filters = [new PIXI.filters.BlurFilter(blurSize)];
const bounds = new PIXI.Rectangle(0, 0, (radius + blurSize) * 2, (radius + blurSize) * 2);
const texture = app.renderer.generateTexture(circle, PIXI.SCALE_MODES.NEAREST, 1, bounds);
const focus = new PIXI.Sprite(texture);
app.stage.addChild(focus);
background.mask = focus;
app.stage.interactive = true;
app.stage.on('mousemove', pointerMove);
function pointerMove(event) {
focus.position.x = event.data.global.x - focus.width / 2;
focus.position.y = event.data.global.y - focus.height / 2;
}
}

Related

How to enable react state to update a chartjs label?

Trying to update the text in the center of a doughnut chart when the prop month changes.
Screenshot of chart, as you can see January did not update, but price did.
However chartJS never updates past the initial month, January, even though it will update when the data changes.
const plugins = [{
beforeDraw: (chart: any) => {
var width = chart.width,
height = chart.height,
ctx = chart.ctx;
ctx.restore();
var price = chart.config.data.datasets[0].data[0];
var item = month;
//Price
var fontSize = (height / 200).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "top";
var text = `$${price.toFixed(2)}`,
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.save();
// Item Type
fontSize = (height / 400).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "top";
text = `${item}`;
textX = Math.round((width - ctx.measureText(text).width) / 2);
textY = height / 2 + 50;
ctx.fillText(text, textX, textY);
ctx.save();
}
}];
const chartRef = useRef<Chart>(null);
return <Doughnut
// #ts-ignore
ref={chartRef}
options={options}
data={data}
// #ts-ignore
plugins={plugins}
/>;
How are we supposed to properly pass information to a chartjs component?
I had the same issue and the problem seems to be the beforeDraw() function won't see any change in variables contained outside of it including any data you pass through the parent component. My workaround was to pass the required data you want into the options object that gets passed into the chart. You will then be able to access it in the beforeDraw() function through the automatic chart parameter like so chart.config.options.nameOfUpdatedData
const options = {
...
price,
month,
}
const plugins = [
{
...
beforeDraw: (chart: any) => {
...
const updatedPrice = chart.config.options.price;
const updatedMonth = chart.config.options.month;
}
},
];
return (
<Chart type="doughnut" data={data} options={options} plugins={plugins} />
)

How to limit pan to canvas edges?

I use fabricJS to edit an image, i've already implemented a zoom tool and a pan tool.
The paning method :
if (!this.isStartedAction) return;
var x = ev.e.screenX,
y = ev.e.screenY;
this.canvas.relativePan({ x: x - this.firstPositionPan.x, y: y - this.firstPositionPan.y });
this.firstPositionPan.x = x;
this.firstPositionPan.y = y;
Problem is, regardless if i zoomed or not, when i use the pan i can move my image outside the canvas. I would like to limit the move to the edge of the canvas but i don't know how to do.
Any suggestion?
Try this
canvas.on('mouse:move', function (e) {
if (isPanning && e && e.e) {
var delta = new fabric.Point(e.e.movementX, e.e.movementY);
canvas.relativePan(delta);
var canvasViewPort = canvas.viewportTransform;
var imageHeight = canvas.height * canvasViewPort[0];
var imageWidth = canvas.width * canvasViewPort[0];
var bottomEndPoint = canvas.height * (canvasViewPort[0] - 1);
if(canvasViewPort[5] >= 0 || -bottomEndPoint > canvasViewPort[5]) {
canvasViewPort[5] = (canvasViewPort[5] >= 0) ? 0 : -bottomEndPoint;
}
var rightEndPoint = canvas.width * (canvasViewPort[0] - 1);
if(canvasViewPort[4] >= 0 || -rightEndPoint > canvasViewPort[4]) {
canvasViewPort[4] = (canvasViewPort[4] >= 0) ? 0 : -rightEndPoint;
}
}
});

Calculate the bounding box of STL file with JavaScript

So I am using this npm package: node-stl
And its working great. However the regexp syntax, mathematics and geometrical calculations are somewhat confusing to me. Especially all at the same time.
Basically what I want to achieve is to extend the script to calculate the bounding box of the STL.
Here is the main file that calculates the volume and weight of the STL being parsed/read.
var fs = require('fs');
// Vertex
function Vertex (v1,v2,v3) {
this.v1 = Number(v1);
this.v2 = Number(v2);
this.v3 = Number(v3);
}
// Vertex Holder
function VertexHolder (vertex1,vertex2,vertex3) {
this.vert1 = vertex1;
this.vert2 = vertex2;
this.vert3 = vertex3;
}
// transforming a Node.js Buffer into a V8 array buffer
function _toArrayBuffer (buffer) {
var
ab = new ArrayBuffer(buffer.length),
view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
view[i] = buffer[i];
}
return ab;
}
// calculation of the triangle volume
// source: http://stackoverflow.com/questions/6518404/how-do-i-calculate-the-volume-of-an-object-stored-in-stl-files
function _triangleVolume (vertexHolder) {
var
v321 = Number(vertexHolder.vert3.v1 * vertexHolder.vert2.v2 * vertexHolder.vert1.v3),
v231 = Number(vertexHolder.vert2.v1 * vertexHolder.vert3.v2 * vertexHolder.vert1.v3),
v312 = Number(vertexHolder.vert3.v1 * vertexHolder.vert1.v2 * vertexHolder.vert2.v3),
v132 = Number(vertexHolder.vert1.v1 * vertexHolder.vert3.v2 * vertexHolder.vert2.v3),
v213 = Number(vertexHolder.vert2.v1 * vertexHolder.vert1.v2 * vertexHolder.vert3.v3),
v123 = Number(vertexHolder.vert1.v1 * vertexHolder.vert2.v2 * vertexHolder.vert3.v3);
return Number(1.0/6.0)*(-v321 + v231 + v312 - v132 - v213 + v123);
}
// parsing an STL ASCII string
function _parseSTLString (stl) {
var totalVol = 0;
// yes, this is the regular expression, matching the vertexes
// it was kind of tricky but it is fast and does the job
var vertexes = stl.match(/facet\s+normal\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+outer\s+loop\s+vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+endloop\s+endfacet/g);
vertexes.forEach(function (vert) {
var preVertexHolder = new VertexHolder();
vert.match(/vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s/g).forEach(function (vertex, i) {
var tempVertex = vertex.replace('vertex', '').match(/[-+]?[0-9]*\.?[0-9]+/g);
var preVertex = new Vertex(tempVertex[0],tempVertex[1],tempVertex[2]);
preVertexHolder['vert'+(i+1)] = preVertex;
});
var partVolume = _triangleVolume(preVertexHolder);
totalVol += Number(partVolume);
})
var volumeTotal = Math.abs(totalVol)/1000;
return {
volume: volumeTotal, // cubic cm
weight: volumeTotal * 1.04 // gm
}
}
// parsing an STL Binary File
// (borrowed some code from here: https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/STLLoader.js)
function _parseSTLBinary (buf) {
buf = _toArrayBuffer(buf);
var
headerLength = 80,
dataOffset = 84,
faceLength = 12*4 + 2,
le = true; // is little-endian
var
dvTriangleCount = new DataView(buf, headerLength, 4),
numTriangles = dvTriangleCount.getUint32(0, le),
totalVol = 0;
for (var i = 0; i < numTriangles; i++) {
var
dv = new DataView(buf, dataOffset + i*faceLength, faceLength),
normal = new Vertex(dv.getFloat32(0, le), dv.getFloat32(4, le), dv.getFloat32(8, le)),
vertHolder = new VertexHolder();
for(var v = 3; v < 12; v+=3) {
var vert = new Vertex(dv.getFloat32(v*4, le), dv.getFloat32((v+1)*4, le), dv.getFloat32( (v+2)*4, le ) );
vertHolder['vert'+(v/3)] = vert;
}
totalVol += _triangleVolume(vertHolder);
}
var volumeTotal = Math.abs(totalVol)/1000;
return {
volume: volumeTotal, // cubic cm
weight: volumeTotal * 1.04 // gm
}
}
// NodeStl
// =======
// > var stl = NodeStl(__dirname + '/myCool.stl');
// > console.log(stl.volume + 'cm^3');
// > console.log(stl.weight + 'gm');
function NodeStl (stlPath) {
var
buf = fs.readFileSync(stlPath),
isAscii = true;
for (var i=0, len=buf.length; i<len; i++) {
if (buf[i] > 127) { isAscii=false; break; }
}
if (isAscii)
return _parseSTLString(buf.toString());
else
return _parseSTLBinary(buf);
}
module.exports = NodeStl;
If anyone could help me with this it would be great. I know and it feels like it simple. That I just need to know max/min of the different directions(x,y,z) and could then calculate the bounding box.
But I do not understand what the max/min for x,y and z is here. Please answer if you have an idea.
I've made a new branch https://github.com/johannesboyne/node-stl/tree/boundingbox could you please verify whether the applied algorithm works?
Best,
Johannes
Edit: If the branch is stable -> works I'll push it into v.0.1.0 (don't know why it is still 0.0.1)

How to generate a "thick" bezier curve?

I'm looking for a way to generate a polygon programatically by "thickening" a Bezier curve. Something like this:
My initial idea was to find the normals in the line, and generate the polygon from them:
But the problem is that the normals can cross each other in steep curves, like this:
Are there any formulas or algorithms that generate a polygon from a bezier curve? I couldn't find any information on the internet, but perhaps I'm searching using the wrong words...
If you want a constant thickness, this is called an offset curve and your idea of using normals is correct.
This indeed raises two difficulties:
The offset curve is not exactly representable as a Bezier curve; you can use a polyline instead, or retrofit Beziers to the polyline;
There are indeed cusps appearing when the radius of curvature becomes smaller than the offset width. You will have to detect the self-intersections of the polyline.
As far as I know, there is no easy solution.
For a little more info, check 38. Curve offsetting.
Step-by-step process detailed here: How to Draw an Offset Curve
Solution based on the paper ‘Quadratic bezier offsetting with selective subdivision‘ by Gabriel Suchowolski. More from the author: MATH+CODE
Interactive example: CodePen
var canvas, ctx;
var drags;
var thickness = 30;
var drawControlPoints = true;
var useSplitCurve = true;
function init() {
canvas = document.createElement('canvas');
ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
drags = [];
window.addEventListener('resize', resize);
window.addEventListener('mousedown', mousedown);
window.addEventListener('mouseup', mouseup);
window.addEventListener('mousemove', mousemove);
document.getElementById('btnControl').addEventListener('click', function(e) {
drawControlPoints = !drawControlPoints
});
document.getElementById('btnSplit').addEventListener('click', function(e) {
useSplitCurve = !useSplitCurve
});
resize();
draw();
var positions = [{
x: canvas.width * 0.3,
y: canvas.height * 0.4
}, {
x: canvas.width * 0.35,
y: canvas.height * 0.85
}, {
x: canvas.width * 0.7,
y: canvas.height * 0.25
}];
for (var i = 0; i < positions.length; i++) {
drags.push(new Drag(ctx, new Vec2D(positions[i].x, positions[i].y)));
}
}
function draw() {
requestAnimationFrame(draw);
ctx.fillStyle = '#FFFFFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.lineWidth = 1;
for (var i = 0; i < drags.length; i++) {
d = drags[i];
d.draw();
}
for (var i = 1; i < drags.length - 1; i++) {
/*
var d1 = (i == 0) ? drags[i].pos : drags[i - 1].pos;
var d2 = drags[i].pos;
var d3 = (i == drags.length - 1) ? drags[drags.length - 1].pos : drags[i + 1].pos;
var v1 = d2.sub(d1);
var v2 = d3.sub(d2);
var p1 = d2.sub(v1.scale(0.5));
var p2 = d3.sub(v2.scale(0.5));
var c = d2;
*/
var p1 = drags[i - 1].pos;
var p2 = drags[i + 1].pos;
var c = drags[i].pos;
var v1 = c.sub(p1);
var v2 = p2.sub(c);
var n1 = v1.normalizeTo(thickness).getPerpendicular();
var n2 = v2.normalizeTo(thickness).getPerpendicular();
var p1a = p1.add(n1);
var p1b = p1.sub(n1);
var p2a = p2.add(n2);
var p2b = p2.sub(n2);
var c1a = c.add(n1);
var c1b = c.sub(n1);
var c2a = c.add(n2);
var c2b = c.sub(n2);
var line1a = new Line2D(p1a, c1a);
var line1b = new Line2D(p1b, c1b);
var line2a = new Line2D(p2a, c2a);
var line2b = new Line2D(p2b, c2b);
var split = (useSplitCurve && v1.angleBetween(v2, true) > Math.PI / 2);
if (!split) {
var ca = line1a.intersectLine(line2a).pos;
var cb = line1b.intersectLine(line2b).pos;
} else {
var t = MathUtils.getNearestPoint(p1, c, p2);
var pt = MathUtils.getPointInQuadraticCurve(t, p1, c, p2);
var t1 = p1.scale(1 - t).add(c.scale(t));
var t2 = c.scale(1 - t).add(p2.scale(t));
var vt = t2.sub(t1).normalizeTo(thickness).getPerpendicular();
var qa = pt.add(vt);
var qb = pt.sub(vt);
var lineqa = new Line2D(qa, qa.add(vt.getPerpendicular()));
var lineqb = new Line2D(qb, qb.add(vt.getPerpendicular()));
var q1a = line1a.intersectLine(lineqa).pos;
var q2a = line2a.intersectLine(lineqa).pos;
var q1b = line1b.intersectLine(lineqb).pos;
var q2b = line2b.intersectLine(lineqb).pos;
}
if (drawControlPoints) {
// draw control points
var r = 2;
ctx.beginPath();
if (!split) {
ctx.rect(ca.x - r, ca.y - r, r * 2, r * 2);
ctx.rect(cb.x - r, cb.y - r, r * 2, r * 2);
} else {
// ctx.rect(pt.x - r, pt.y - r, r * 2, r * 2);
ctx.rect(p1a.x - r, p1a.y - r, r * 2, r * 2);
ctx.rect(q1a.x - r, q1a.y - r, r * 2, r * 2);
ctx.rect(p2a.x - r, p2a.y - r, r * 2, r * 2);
ctx.rect(q2a.x - r, q2a.y - r, r * 2, r * 2);
ctx.rect(qa.x - r, qa.y - r, r * 2, r * 2);
ctx.rect(p1b.x - r, p1b.y - r, r * 2, r * 2);
ctx.rect(q1b.x - r, q1b.y - r, r * 2, r * 2);
ctx.rect(p2b.x - r, p2b.y - r, r * 2, r * 2);
ctx.rect(q2b.x - r, q2b.y - r, r * 2, r * 2);
ctx.rect(qb.x - r, qb.y - r, r * 2, r * 2);
ctx.moveTo(qa.x, qa.y);
ctx.lineTo(qb.x, qb.y);
}
ctx.closePath();
ctx.strokeStyle = '#0072bc';
ctx.stroke();
ctx.fillStyle = '#0072bc';
ctx.fill();
// draw dashed lines
ctx.beginPath();
if (!split) {
ctx.moveTo(p1a.x, p1a.y);
ctx.lineTo(ca.x, ca.y);
ctx.lineTo(p2a.x, p2a.y);
ctx.moveTo(p1b.x, p1b.y);
ctx.lineTo(cb.x, cb.y);
ctx.lineTo(p2b.x, p2b.y);
} else {
ctx.moveTo(p1a.x, p1a.y);
ctx.lineTo(q1a.x, q1a.y);
ctx.lineTo(qa.x, qa.y);
ctx.lineTo(q2a.x, q2a.y);
ctx.lineTo(p2a.x, p2a.y);
ctx.moveTo(p1b.x, p1b.y);
ctx.lineTo(q1b.x, q1b.y);
ctx.lineTo(qb.x, qb.y);
ctx.lineTo(q2b.x, q2b.y);
ctx.lineTo(p2b.x, p2b.y);
}
ctx.setLineDash([2, 4]);
ctx.stroke();
ctx.closePath();
ctx.setLineDash([]);
}
// central line
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.quadraticCurveTo(c.x, c.y, p2.x, p2.y);
ctx.strokeStyle = '#959595';
ctx.stroke();
// offset curve a
ctx.beginPath();
ctx.moveTo(p1a.x, p1a.y);
if (!split) {
ctx.quadraticCurveTo(ca.x, ca.y, p2a.x, p2a.y);
} else {
ctx.quadraticCurveTo(q1a.x, q1a.y, qa.x, qa.y);
ctx.quadraticCurveTo(q2a.x, q2a.y, p2a.x, p2a.y);
}
ctx.strokeStyle = '#0072bc';
ctx.lineWidth = 2;
ctx.stroke();
// offset curve b
ctx.beginPath();
ctx.moveTo(p1b.x, p1b.y);
if (!split) {
ctx.quadraticCurveTo(cb.x, cb.y, p2b.x, p2b.y);
} else {
ctx.quadraticCurveTo(q1b.x, q1b.y, qb.x, qb.y);
ctx.quadraticCurveTo(q2b.x, q2b.y, p2b.x, p2b.y);
}
ctx.strokeStyle = '#0072bc';
ctx.stroke();
}
}
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
function mousedown(e) {
e.preventDefault();
var m = new Vec2D(e.clientX, e.clientY);
for (var i = 0; i < drags.length; i++) {
var d = drags[i];
var dist = d.pos.distanceToSquared(m);
if (dist < d.hitRadiusSq) {
d.down = true;
break;
}
}
}
function mouseup() {
for (var i = 0; i < drags.length; i++) {
var d = drags[i];
d.down = false;
}
}
function mousemove(e) {
var m = new Vec2D(e.clientX, e.clientY);
for (var i = 0; i < drags.length; i++) {
var d = drags[i];
if (d.down) {
d.pos.x = m.x;
d.pos.y = m.y;
break;
}
}
}
function Drag(ctx, pos) {
this.ctx = ctx;
this.pos = pos;
this.radius = 6;
this.hitRadiusSq = 900;
this.down = false;
}
Drag.prototype = {
draw: function() {
this.ctx.beginPath();
this.ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI * 2);
this.ctx.closePath();
this.ctx.strokeStyle = '#959595'
this.ctx.stroke();
}
}
// http://toxiclibs.org/docs/core/toxi/geom/Vec2D.html
function Vec2D(a, b) {
this.x = a;
this.y = b;
}
Vec2D.prototype = {
add: function(a) {
return new Vec2D(this.x + a.x, this.y + a.y);
},
angleBetween: function(v, faceNormalize) {
if (faceNormalize === undefined) {
var dot = this.dot(v);
return Math.acos(this.dot(v));
}
var theta = (faceNormalize) ? this.getNormalized().dot(v.getNormalized()) : this.dot(v);
return Math.acos(theta);
},
distanceToSquared: function(v) {
if (v !== undefined) {
var dx = this.x - v.x;
var dy = this.y - v.y;
return dx * dx + dy * dy;
} else {
return NaN;
}
},
dot: function(v) {
return this.x * v.x + this.y * v.y;
},
getNormalized: function() {
return new Vec2D(this.x, this.y).normalize();
},
getPerpendicular: function() {
return new Vec2D(this.x, this.y).perpendicular();
},
interpolateTo: function(v, f) {
return new Vec2D(this.x + (v.x - this.x) * f, this.y + (v.y - this.y) * f);
},
normalize: function() {
var mag = this.x * this.x + this.y * this.y;
if (mag > 0) {
mag = 1.0 / Math.sqrt(mag);
this.x *= mag;
this.y *= mag;
}
return this;
},
normalizeTo: function(len) {
var mag = Math.sqrt(this.x * this.x + this.y * this.y);
if (mag > 0) {
mag = len / mag;
this.x *= mag;
this.y *= mag;
}
return this;
},
perpendicular: function() {
var t = this.x;
this.x = -this.y;
this.y = t;
return this;
},
scale: function(a) {
return new Vec2D(this.x * a, this.y * a);
},
sub: function(a, b) {
return new Vec2D(this.x - a.x, this.y - a.y);
},
}
// http://toxiclibs.org/docs/core/toxi/geom/Line2D.html
function Line2D(a, b) {
this.a = a;
this.b = b;
}
Line2D.prototype = {
intersectLine: function(l) {
var isec,
denom = (l.b.y - l.a.y) * (this.b.x - this.a.x) - (l.b.x - l.a.x) * (this.b.y - this.a.y),
na = (l.b.x - l.a.x) * (this.a.y - l.a.y) - (l.b.y - l.a.y) * (this.a.x - l.a.x),
nb = (this.b.x - this.a.x) * (this.a.y - l.a.y) - (this.b.y - this.a.y) * (this.a.x - l.a.x);
if (denom !== 0) {
var ua = na / denom,
ub = nb / denom;
if (ua >= 0.0 && ua <= 1.0 && ub >= 0.0 && ub <= 1.0) {
isec = new Line2D.LineIntersection(Line2D.LineIntersection.Type.INTERSECTING, this.a.interpolateTo(this.b, ua));
} else {
isec = new Line2D.LineIntersection(Line2D.LineIntersection.Type.NON_INTERSECTING, this.a.interpolateTo(this.b, ua));
}
} else {
if (na === 0 && nb === 0) {
isec = new Line2D.LineIntersection(Line2D.LineIntersection.Type.COINCIDENT, undefined);
} else {
isec = new Line2D.LineIntersection(Line2D.LineIntersection.Type.COINCIDENT, undefined);
}
}
return isec;
}
}
Line2D.LineIntersection = function(type, pos) {
this.type = type;
this.pos = pos;
}
Line2D.LineIntersection.Type = {
COINCIDENT: 0,
PARALLEL: 1,
NON_INTERSECTING: 2,
INTERSECTING: 3
};
window.MathUtils = {
getPointInQuadraticCurve: function(t, p1, pc, p2) {
var x = (1 - t) * (1 - t) * p1.x + 2 * (1 - t) * t * pc.x + t * t * p2.x;
var y = (1 - t) * (1 - t) * p1.y + 2 * (1 - t) * t * pc.y + t * t * p2.y;
return new Vec2D(x, y);
},
// http://microbians.com/math/Gabriel_Suchowolski_Quadratic_bezier_offsetting_with_selective_subdivision.pdf
// http://www.math.vanderbilt.edu/~schectex/courses/cubic/
getNearestPoint: function(p1, pc, p2) {
var v0 = pc.sub(p1);
var v1 = p2.sub(pc);
var a = v1.sub(v0).dot(v1.sub(v0));
var b = 3 * (v1.dot(v0) - v0.dot(v0));
var c = 3 * v0.dot(v0) - v1.dot(v0);
var d = -1 * v0.dot(v0);
var p = -b / (3 * a);
var q = p * p * p + (b * c - 3 * a * d) / (6 * a * a);
var r = c / (3 * a);
var s = Math.sqrt(q * q + Math.pow(r - p * p, 3));
var t = MathUtils.cbrt(q + s) + MathUtils.cbrt(q - s) + p;
return t;
},
// http://stackoverflow.com/questions/12810765/calculating-cubic-root-for-negative-number
cbrt: function(x) {
var sign = x === 0 ? 0 : x > 0 ? 1 : -1;
return sign * Math.pow(Math.abs(x), 1 / 3);
}
}
init();
html,
body {
height: 100%;
margin: 0
}
canvas {
display: block
}
#btnControl {
position: absolute;
top: 10px;
left: 10px;
}
#btnSplit {
position: absolute;
top: 35px;
left: 10px;
}
<button type="button" id="btnControl">control points on/off</button>
<button type="button" id="btnSplit">split curve on/off</button>
This is a hard problem. There are reasonable approximations like Tiller-Hanson (see my answer to this question: How to get the outline of a stroke?) but the questioner specifically raises the difficulty that 'the normals can cross each other in steep curves'; another way of looking at it is that an envelope created using normals can produce an indefinitely large number of loops, depending on how closely spaced the normals are.
A perfect solution, without self-intersections, is the envelope of the Minkowski sum of a circle and the line. I think it's impractical to get such an envelope, though: you may have to accept the intersections.
Another interesting but daunting fact is that, as Richard Kinch notes in MetaFog: Converting METAFONT Shapes to Contours, "Algebra tells us
that stroking a 3rd degree polynomial curve (the ellipse
approximated by Bézier curves) along a 3rd
degree polynomial curve (the Bézier curve of the
stroked path) results in a 6th degree envelope curve.
We will have to approximate these 6th degree exact
envelope curves with 3rd degree (Bezier) curves".
Here I had the math papers about that theme.
The “Quadratic bezier offsetting with selective subdivision" covers a method to offset quadratic beziers using a criterion that set the parametric value on which the quadratic bezier is subdivided at the start in order to generate an offset approximation with other quadratic beziers segments. This method, obviously, may not be the most perfect approximation of a hypothetical “real” offset, but a fast algorithm for drawing strokes that can be performed on different quality levels by using a non recursive algorithm.
Here all the papers and examples https://microbians.com/mathcode
that imbrizi use for the codepen he put in the answers.
https://codepen.io/microbians/pen/OJPmBZg
code in the link

How can I remove all SVG elements which do not intersect a particular rectangle?

I have an SVG image from which I'd like to extract several rectangular regions as independent SVG images. Because the original image is rather large but the elements intersecting the areas of interest are small, I do not want elements which lie entirely outside the cropped viewBox to remain in the cropped SVG image.
Conceptually, what I'm looking for is this:
The cropped SVG (yes, the output must be SVG, not a bitmap) should not contain elements for the spiral or the star, as they fall entirely outside the area of interest. (Yes, the nonintersecting elements really must be removed, due to the source SVG being several orders of magnitude more bytes than the cropped SVG, as I intend to crop the source in different ways hundreds of times.) I want to be able to specify the area of interest on the command-line, as well, due to having quite a number of such cropped images to produce.
Are there any tools which can do this?
SVG elements can be parsed and flagged true/false as inside a svg rect object and/or intersecting the rect object.
Would this work for you?
isEnclosed = mySVG.checkEnclosure(myElement, RectObj)
doesIntersect = mySVG.checkIntersection(myElement, RectObj)
I use the Jordan Curve Theorem to test for points inside an svg polygon. Your polygon would be your viewBox. Posssibly this could work for you if each element has a target point associated with it(i.e. center point) to determine if you want to show it or not.
The following is the javascript I use:(caution: I think the polygon should have counter-clockwise points. Always a good idea when dealing with polygons)
//---Point-in-polygon: Jordan Curve Theorem---
function pointInPolygon(myPolygon,px,py)
{
var pointsList=myPolygon.points
var x
var y
var x1
var y1
var crossings=0
var verts=pointsList.numberOfItems
//---Iterate through each line ---
for ( var i = 0; i < verts; i++ )
{
var vertx=pointsList.getItem(i).x
var verty=pointsList.getItem(i).y
if(i<verts-1)
{
var vertxNext=pointsList.getItem(i+1).x
var vertyNext=pointsList.getItem(i+1).y
}
else
{
var vertxNext=pointsList.getItem(0).x
var vertyNext=pointsList.getItem(0).y
}
/* This is done to ensure that we get the same result when
the line goes from left to right and right to left */
if ( vertx < vertxNext){
x1 = vertx;
x2 = vertxNext;
} else {
x1 = vertxNext;
x2 = vertx;
}
/* First check if the ray is possible to cross the line */
if ( px > x1 && px <= x2 && ( py < verty || py <= vertyNext ) ) {
var eps = 0.000000001;
/* Calculate the equation of the line */
var dx = vertxNext - vertx;
var dy = vertyNext - verty;
var k;
if ( Math.abs(dx) < eps ){
k = Infinity;
} else {
k = dy/dx;
}
var m = verty - k * vertx;
/* Find if the ray crosses the line */
y2 = k * px + m;
if ( py <= y2 ){
crossings++;
}
}
}
//---odd number of crossings: point inside polygon--
var crossFlag=(crossings/2)+""
if(crossFlag.indexOf(".")!=-1)
return true;
else
return false;
}
Since your svg elements are transformed, you may need to convert them to screen points. I've used the following javascript for the various svg elements(line, rect, circle, ellipse, polygon, polyline, and path)
//----build a generic document SVG root to hold svg point---
function screenLine(line,svg)
{
var sCTM = line.getCTM()
var x1=parseFloat(line.getAttribute("x1"))
var y1=parseFloat(line.getAttribute("y1"))
var x2=parseFloat(line.getAttribute("x2"))
var y2=parseFloat(line.getAttribute("y2"))
var mySVGPoint1 = svg.createSVGPoint();
mySVGPoint1.x = x1
mySVGPoint1.y = y1
mySVGPointTrans1 = mySVGPoint1.matrixTransform(sCTM)
line.setAttribute("x1",mySVGPointTrans1.x)
line.setAttribute("y1",mySVGPointTrans1.y)
var mySVGPoint2 = svg.createSVGPoint();
mySVGPoint2.x = x2
mySVGPoint2.y = y2
mySVGPointTrans2= mySVGPoint2.matrixTransform(sCTM)
line.setAttribute("x2",mySVGPointTrans2.x)
line.setAttribute("y2",mySVGPointTrans2.y)
//---force removal of transform--
line.setAttribute("transform","")
line.removeAttribute("transform")
}
function screenCircle(circle,svg)
{
var sCTM = circle.getCTM()
var scaleX = sCTM.a;
var cx=parseFloat(circle.getAttribute("cx"))
var cy=parseFloat(circle.getAttribute("cy"))
var r=parseFloat(circle.getAttribute("r"))
var mySVGPointC = svg.createSVGPoint();
mySVGPointC.x = cx
mySVGPointC.y = cy
mySVGPointTransC = mySVGPointC.matrixTransform(sCTM)
circle.setAttribute("cx",mySVGPointTransC.x)
circle.setAttribute("cy",mySVGPointTransC.y)
circle.setAttribute("r",r*scaleX)
//---force removal of transform--
circle.setAttribute("transform","")
circle.removeAttribute("transform")
}
function screenEllipse(ellipse,svg)
{
var sCTM = ellipse.getCTM()
var scaleX = sCTM.a;
var scaleY = sCTM.d;
var cx=parseFloat(ellipse.getAttribute("cx"))
var cy=parseFloat(ellipse.getAttribute("cy"))
var rx=parseFloat(ellipse.getAttribute("rx"))
var ry=parseFloat(ellipse.getAttribute("ry"))
var mySVGPointC = svg.createSVGPoint();
mySVGPointC.x = cx
mySVGPointC.y = cy
mySVGPointTransC = mySVGPointC.matrixTransform(sCTM)
ellipse.setAttribute("cx",mySVGPointTransC.x)
ellipse.setAttribute("cy",mySVGPointTransC.y)
ellipse.setAttribute("rx",rx*scaleX)
ellipse.setAttribute("ry",ry*scaleY)
//---force removal of transform--
ellipse.setAttribute("transform","")
ellipse.removeAttribute("transform")
}
function screenRect(rect,svg)
{
var sCTM = rect.getCTM()
var scaleX = sCTM.a;
var scaleY = sCTM.d;
var x=parseFloat(rect.getAttribute("x"))
var y=parseFloat(rect.getAttribute("y"))
var width=parseFloat(rect.getAttribute("width"))
var height=parseFloat(rect.getAttribute("height"))
var mySVGPoint = svg.createSVGPoint();
mySVGPoint.x = x
mySVGPoint.y = y
mySVGPointTrans = mySVGPoint.matrixTransform(sCTM)
rect.setAttribute("x",mySVGPointTrans.x)
rect.setAttribute("y",mySVGPointTrans.y)
rect.setAttribute("width",width*scaleX)
rect.setAttribute("height",height*scaleY)
//---force removal of transform--
rect.setAttribute("transform","")
rect.removeAttribute("transform")
}
function screenPolyline(myPoly,svg)
{
var sCTM = myPoly.getCTM()
var pointsList = myPoly.points;
var n = pointsList.numberOfItems;
for(var m=0;m<n;m++)
{
var mySVGPoint = mySVG.createSVGPoint();
mySVGPoint.x = pointsList.getItem(m).x
mySVGPoint.y = pointsList.getItem(m).y
mySVGPointTrans = mySVGPoint.matrixTransform(sCTM)
pointsList.getItem(m).x=mySVGPointTrans.x
pointsList.getItem(m).y=mySVGPointTrans.y
}
//---force removal of transform--
myPoly.setAttribute("transform","")
myPoly.removeAttribute("transform")
}
function screenPath(path,svg)
{
var sCTM = path.getCTM()
var scaleX = sCTM.a;
var scaleY = sCTM.d;
var segList=path.pathSegList
var segs=segList.numberOfItems
//---change segObj values
for(var k=0;k<segs;k++)
{
var segObj=segList.getItem(k)
if(segObj.x && segObj.y )
{
var mySVGPoint = svg.createSVGPoint();
mySVGPoint.x = segObj.x
mySVGPoint.y = segObj.y
mySVGPointTrans = mySVGPoint.matrixTransform(sCTM)
segObj.x=mySVGPointTrans.x
segObj.y=mySVGPointTrans.y
}
if(segObj.x1 && segObj.y1)
{
var mySVGPoint1 = svg.createSVGPoint();
mySVGPoint1.x = segObj.x1
mySVGPoint1.y = segObj.y1
mySVGPointTrans1 = mySVGPoint1.matrixTransform(sCTM)
segObj.x1=mySVGPointTrans1.x
segObj.y1=mySVGPointTrans1.y
}
if(segObj.x2 && segObj.y2)
{
var mySVGPoint2 = svg.createSVGPoint();
mySVGPoint2.x = segObj.x2
mySVGPoint2.y = segObj.y2
mySVGPointTrans2 = mySVGPoint2.matrixTransform(sCTM)
segObj.x2=mySVGPointTrans2.x
segObj.y2=mySVGPointTrans2.y
}
if(segObj.r1)segObj.r1=segObj.r1*scaleX
if(segObj.r2)segObj.r2=segObj.r2*scaleX
}
//---force removal of transform--
path.setAttribute("transform","")
path.removeAttribute("transform")
}
//---changes all transformed points to screen points---
function screenPolygon(myPoly,mySVG)
{
var sCTM = myPoly.getCTM()
var pointsList = myPoly.points;
var n = pointsList.numberOfItems;
for(var m=0;m<n;m++)
{
var mySVGPoint = mySVG.createSVGPoint();
mySVGPoint.x = pointsList.getItem(m).x
mySVGPoint.y = pointsList.getItem(m).y
mySVGPointTrans = mySVGPoint.matrixTransform(sCTM)
pointsList.getItem(m).x=mySVGPointTrans.x
pointsList.getItem(m).y=mySVGPointTrans.y
}
//---force removal of transform--
myPoly.setAttribute("transform","")
myPoly.removeAttribute("transform")
}

Resources