Is there a way to create a gradient in basiljs? - adobe-indesign

It's a pretty self-explanatory question.
I am curious as to why there is no built-in function to create gradients. The only way I found to "fake it" is to create a series of lines or rectangles each with a unique color calculated with b.lerpColor.
I saw that the InDesign Object Model has of course the gradient class but I don't know how to access it using basiljs.
Maybe if someone could show me? Many thanks.

Check out this reference http://jongware.mit.edu/idcs6js/pc_Gradient.html
And try it like this:
#includepath "~/Documents/;%USERPROFILE%Documents";
#include "basiljs/bundle/basil.js";
function draw() {
var d = b.doc();
var r = b.rect(0, 0, b.width, b.height);
var myGrad = d.gradients.add({
name: "Col " + (parseInt(Math.random() * 10000)),
type: GradientType.linear
});
myGrad.gradientStops[0].properties = {
stopColor: d.colors.item(2),
location: Math.random() * 50
};
myGrad.gradientStops[1].properties = {
stopColor: d.colors.item(4),
location: 50 + Math.random() * 50
};
r.fillColor = myGrad;
// to set the fill of the gradient use the following line
r.gradientFillAngle = 50;//b.random(-180,180);
}
b.go();
The script creates a new gradient swatch every time you run it.
edit:added gradientFillAngle
Take a look here.
gradientFillAngle number r/w The angle of a linear gradient applied to the fill of the Rectangle. (Range: -180 to 180)

Related

Buildings in three.js

I am working on a web game and using three.js to do the 3d of the game. I am building a city and I want the buildings to look exactly like the picture below.
I want them to be a base material, without textures or colors because I will add colors later depending on the building status (like the game below).
This is what I have right now:
As you can see, I just have a bunch of different-sized boxes, with no details at all. How would I achieve the details seen in the game?
This is my current code:
export default function Map() {
const RenderBuildings = () => {
const buildings = []
for (let i = 0; i < 10; i++) {
buildings.push(<Box color="#dad3cb" width={1} height={1} depth={1} />)
}
return buildings
}
return (
<Canvas>
<CameraController />
<ambientLight intensity={1} />
<Ground color="#b0aa9d" width={40} height={1} depth={40} />
{RenderBuildings()}
</Canvas>
)
}
export const Box = (props: Props) => {
const { color, width, height, depth, ...rest } = props
const mesh = useRef<THREE.Mesh>()
const boxRef = useRef<THREE.Mesh>()
useEffect(() => {
if (!mesh.current) return
const _mesh = mesh.current
_mesh.position.x = Math.floor(Math.random() * 20)
_mesh.position.z = Math.floor(Math.random() * 20)
_mesh.scale.x =
Math.random() * Math.random() * Math.random() * Math.random() * 5 + 3
_mesh.scale.z = _mesh.scale.x
_mesh.scale.y =
Math.random() * Math.random() * Math.random() * _mesh.scale.x * 5 + 3
}, [mesh])
useEffect(() => {
if (!boxRef.current) return
const _boxRef = boxRef.current
_boxRef.applyMatrix4(new Matrix4().makeTranslation(0, 0.5, 0))
}, [boxRef])
return (
<mesh {...rest} ref={mesh}>
<boxGeometry args={[width, height, depth]} ref={boxRef} />
<meshToonMaterial color={color} />
</mesh>
)
}
Your first step should be to look at lighting your scene. This will allow for better depth to your buildings. A hemisphere light may be your best bet: https://threejs.org/examples/#webgl_lights_hemisphere. You can learn more about lights here: https://threejs.org/manual/#en/lights.
Next, take a look at geometry. You want those buildings to have some level of detail at the geometry level. You can use primitives like these: https://threejs.org/manual/#en/primitives or build a model in any modelling software and import it in. At that point, maybe make a few models and then instance them randomly.
Depending on how you do geometry, you will need to pick an appropriate material: https://threejs.org/manual/#en/materials. This should give you plenty of options.
I would also add in a bit of animation to keep things lively: https://threejs.org/examples/#webgl_animation_keyframes
Finally, a bit of fog always helps for ambiance: https://threejs.org/manual/#en/fog
Some more inspiration: https://demos.littleworkshop.fr/infinitown
Ultimately, building a scene like this is going to be a labour of love. There are no easy shortcuts. Keep at it!
Use a texture tile(s) to coordinate the layout (like a QR code but unencrypted). That is, a ~64x64 image with RGB values which correspond to scene logic. This method will be easier to block in features. You can store height in R, type in G, and owner in B. Maybe there is a sidecar file with more raw data (i.e. bills or level), referenced by owner and x/y.
Map generation could be defined by: matrix, random forest, evolutions... with rules for adjacent tiles and minimum areas. Then once you have a satisfactory system, it can be parsed as a Three.js scene. Geometry can be as easy or as hard as you make it. Extrude contiguous pixel groups & refine.
Don't forget to add dust clouds when you synchronize the data to obscure visual artifacts. You can probably do a lot with texture offsets in terms of variety, from a forced perspective.

adding perlin noise to THREE.js r121

I have been struggling with finding a good tutorial to add perlin noise to a newer version of THREE.js. I have found many tutorials and examples but they all seem to break when I add r121 into the mix.
I've tried a great example from Codepen using a script from jeromeetienne.github.io
I've also tried this guys tutorial and file http://www.stephanbaker.com/post/perlinterrain/
I've tried several others and no luck. I am convinced it's due to THREE versions being used. Most of what I can find use an old version of THREE.js. I have forked what others have, and it works with the old version they are using but not the new one.
//land
let landGeo = new THREE.PlaneGeometry(500,500, 50, 50);
let landMat = new THREE.MeshStandardMaterial({
color:'green'
})
land = new THREE.Mesh(landGeo, landMat);
scene.add(land);
noise.seed(Math.random());
for(let i=1;i<100;i++) {
for(let j=1;j<100;j++) {
var value = noise.simplex2(i / 100, j / 100);
// ... or noise.simplex3 and noise.perlin3:
// var value = noise.simplex3(i / 100, j / 100, clock);
landGeo[i][j].r = Math.abs(value) * 256;
}
}
So does anyone know how can get some version of perlin noise working? I am trying to creat terrain.
https://codepen.io/jfirestorm44/pen/mdEEwqb?editors=0010
Thank you
Did you check the browser console errors? It should be the first thing you check.
I see the error Cannot read property '1' of undefined.
Which tells me that something is wrong with the line landGeo[i][j].r = Math.abs(value) * 256;
The vertices are in a single dimension array and are vector objects. I am pretty sure it should be:
landGeo.vertices[i+j].z = Math.abs(value) * 256;.
Also, I am not sure you are calling the noise function with the correct parameters, though I could be wrong and you may be wanting it like it is.
var value = noise.simplex2(i / 100, j / 100);
Also, you are starting your for loops at 1, for(let i=1;i<100;i++) {, I am pretty sure you want to start them at 0. for(let i=0;i<100;i++) {
There is always the option of doing the displacement in a shader like this 3d example, only in 2d

ChartJS line chart calls plugin each time I hover a point

I am using ChartJS v2.9.3.
I am trying to add to the time line chart a conditional vertical background color that is displayed depending on if dataset's y-value is above a threshold.
The thread Background colour of line charts in chart.js gave me the idea to use the following plugin
const backgroundPlugin = {
beforeDatasetDraw(chart, easing) {
const ctx = chart.chart.ctx;
const chartArea = chart.chartArea;
ctx.save();
const colors = [
'red',
'green',
'yellow',
'blue'
];
const randomNumber = Math.floor(Math.random() * colors.length);
// Set random background color to show how many times this function is called
ctx.fillStyle = colors[randomNumber];
console.log('refreshing background');
chart.getDatasetMeta(0).data.forEach((data, index, all) => {
// Check if value > threshold (here 350)
if (
chart.config.data.datasets[0].data[index].y > 350
) {
const nextPointX =
index === all.length - 1 ?
chartArea.left :
all[index + 1]._model.x;
// Create vertical rectangle of color between current point and next point
ctx.fillRect(
nextPointX,
chartArea.top,
Math.abs(all[index]._model.x - nextPointX),
chartArea.bottom - chartArea.top
);
}
});
ctx.restore();
}
};
The problem I observed is that every time I hover on one point of the line chart, the plugin's beforeDatasetDraw function gets called a huge number of time.
The problem can be seen on this JSFiddle : https://jsfiddle.net/avocado1/hgpukame/88/#
This is a problem for me because in my real case that causes a performance issue (I work with a more than 20.000 points datasets and I would like to have 5 different background colors depending on 5 different thresholds, meaning there could be 5 comparisons for each point of my dataset).
Would anyone have any clue on how to prevent hovering events to cause calls to my plugin ? (Or have any workaround to create a conditional background once and for all ?)

d3 synchronizing 2 separate zoom behaviors

I have the following d3/d3fc chart
https://codepen.io/parliament718/pen/BaNQPXx
The chart has a zoom behavior for the main area and a separate zoom behavior for the y-axis.
The y-axis can be dragged to rescale.
The problem I'm having trouble solving is that after dragging the y-axis to rescale and then subsequently panning the chart, there is a "jump" in the chart.
Obviously the 2 zoom behaviors have a disconnect and need to be synchronized but I'm racking my brain trying to fix this.
const mainZoom = zoom()
.on('zoom', () => {
xScale.domain(t.rescaleX(x2).domain());
yScale.domain(t.rescaleY(y2).domain());
});
const yAxisZoom = zoom()
.on('zoom', () => {
const t = event.transform;
yScale.domain(t.rescaleY(y2).domain());
render();
});
const yAxisDrag = drag()
.on('drag', (args) => {
const factor = Math.pow(2, -event.dy * 0.01);
plotArea.call(yAxisZoom.scaleBy, factor);
});
The desired behavior is for zooming, panning, and/or rescaling the axis to always apply the transformation from wherever the previous action finished, without any "jumps".
OK, so I've had another go at this - as mentioned in my previous answer, the biggest issue you need to overcome is that the d3-zoom only permits symmetrical scaling. This is something that has been widely discussed, and I believe Mike Bostock is addressing this in the next release.
So, in order to overcome the issue, you need to use multiple zoom behaviour. I have created a chart that has three, one for each axis and one for the plot area. The X & Y zoom behaviours are used to scale the axes. Whenever a zoom event is raised by the X & Y zoom behaviours, their translation values are copied across to the plot area. Likewise, when a translation occurs on the plot area, the x & y components are copied to the respective axis behaviours.
Scaling on the plot area is a little more complicated as we need to maintain the aspect ratio. In order to achieve this I store the previous zoom transform and use the scale delta to work out a suitable scale to apply to the X & Y zoom behaviours.
For convenience, I've wrapped all of this up into a chart component:
const interactiveChart = (xScale, yScale) => {
const zoom = d3.zoom();
const xZoom = d3.zoom();
const yZoom = d3.zoom();
const chart = fc.chartCartesian(xScale, yScale).decorate(sel => {
const plotAreaNode = sel.select(".plot-area").node();
const xAxisNode = sel.select(".x-axis").node();
const yAxisNode = sel.select(".y-axis").node();
const applyTransform = () => {
// apply the zoom transform from the x-scale
xScale.domain(
d3
.zoomTransform(xAxisNode)
.rescaleX(xScaleOriginal)
.domain()
);
// apply the zoom transform from the y-scale
yScale.domain(
d3
.zoomTransform(yAxisNode)
.rescaleY(yScaleOriginal)
.domain()
);
sel.node().requestRedraw();
};
zoom.on("zoom", () => {
// compute how much the user has zoomed since the last event
const factor = (plotAreaNode.__zoom.k - plotAreaNode.__zoomOld.k) / plotAreaNode.__zoomOld.k;
plotAreaNode.__zoomOld = plotAreaNode.__zoom;
// apply scale to the x & y axis, maintaining their aspect ratio
xAxisNode.__zoom.k = xAxisNode.__zoom.k * (1 + factor);
yAxisNode.__zoom.k = yAxisNode.__zoom.k * (1 + factor);
// apply transform
xAxisNode.__zoom.x = d3.zoomTransform(plotAreaNode).x;
yAxisNode.__zoom.y = d3.zoomTransform(plotAreaNode).y;
applyTransform();
});
xZoom.on("zoom", () => {
plotAreaNode.__zoom.x = d3.zoomTransform(xAxisNode).x;
applyTransform();
});
yZoom.on("zoom", () => {
plotAreaNode.__zoom.y = d3.zoomTransform(yAxisNode).y;
applyTransform();
});
sel
.enter()
.select(".plot-area")
.on("measure.range", () => {
xScaleOriginal.range([0, d3.event.detail.width]);
yScaleOriginal.range([d3.event.detail.height, 0]);
})
.call(zoom);
plotAreaNode.__zoomOld = plotAreaNode.__zoom;
// cannot use enter selection as this pulls data through
sel.selectAll(".y-axis").call(yZoom);
sel.selectAll(".x-axis").call(xZoom);
decorate(sel);
});
let xScaleOriginal = xScale.copy(),
yScaleOriginal = yScale.copy();
let decorate = () => {};
const instance = selection => chart(selection);
// property setters not show
return instance;
};
Here's a pen with the working example:
https://codepen.io/colineberhardt-the-bashful/pen/qBOEEGJ
There are a couple of issues with your code, one which is easy to solve, and one which is not ...
Firstly, the d3-zoom works by storing a transform on the selected DOM element(s) - you can see this via the __zoom property. When the user interacts with the DOM element, this transform is updated and events emitted. Therefore, if you have to different zoom behaviours both of which are controlling the pan / zoom of a single element, you need to keep these transforms synchronised.
You can copy the transform as follows:
selection.call(zoom.transform, d3.event.transform);
However, this will also cause zoom events to be fired from the target behaviour also.
An alternative is to copy directly to the 'stashed' transform property:
selection.node().__zoom = d3.event.transform;
However, there is a bigger problem with what you are trying to achieve. The d3-zoom transform is stored as 3 components of a transformation matrix:
https://github.com/d3/d3-zoom#zoomTransform
As a result, the zoom can only represent a symmetrical scaling together with a translation. Your asymmetrical zoom as a applied to the x-axis cannot be faithfully represented by this transform and re-applied to the plot-area.
This is an upcoming feature, as already noted by #ColinE. The original code is always doing a "temporal zoom" that is un-synced from the transform matrix.
The best workaround is to tweak the xExtent range so that the graph believes that there are additional candles on the sides. This can be achieved by adding pads to the sides. The accessors, instead of being,
[d => d.date]
becomes,
[
() => new Date(taken[0].date.addDays(-xZoom)), // Left pad
d => d.date,
() => new Date(taken[taken.length - 1].date.addDays(xZoom)) // Right pad
]
Sidenote: Note that there is a pad function that should do that but for some reason it works only once and never updates again that's why it is added as an accessors.
Sidenote 2: Function addDays added as a prototype (not the best thing to do) just for simplicity.
Now the zoom event modifies our X zoom factor, xZoom,
zoomFactor = Math.sign(d3.event.sourceEvent.wheelDelta) * -5;
if (zoomFactor) xZoom += zoomFactor;
It is important to read the differential directly from wheelDelta. This is where the unsupported feature is: We can't read from t.x as it will change even if you drag the Y axis.
Finally, recalculate chart.xDomain(xExtent(data.series)); so that the new extent is available.
See the working demo without the jump here: https://codepen.io/adelriosantiago/pen/QWjwRXa?editors=0011
Fixed: Zoom reversing, improved behaviour on trackpad.
Technically you could also tweak yExtent by adding extra d.high and d.low's. Or even both xExtent and yExtent to avoid using the transform matrix at all.
A solution is given here https://observablehq.com/#d3/x-y-zoom
It uses a main zoom behavior that gets the gestures, and two ancillary zooms that store the transforms.

Multiple clipping areas on Fabric.js canvas

For making Photo Collage Maker, I use fabric js which has an object-based clipping feature. This feature is great but the image inside that clipping region cannot be scaled, moved or rotated. I want a fixed position clipping region and the image can be positioned inside the fixed clipping area as the user want.
I googled and find very near solution.
var canvas = new fabric.Canvas('c');
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(10,10,150,150);
ctx.rect(180,10,200,200);
ctx.closePath();
ctx.stroke();
ctx.clip();
Multiple Clipping Areas on fabric js canvas
where the image of one clipping region has appeared in another clipping region. How can I avoid this or is there another way of accomplishing this using fabric js.
This can be accomplished with Fabric using the clipTo property, but you have to 'reverse' the transformations (scale and rotation), in the clipTo function.
When you use the clipTo property in Fabric, the scaling and rotation are applied after the clipping, which means that the clipping is scaled and rotated with the image. You have to counter this by applying the exact reverse of the transformations in the clipTo property function.
My solution involves having a Fabric.Rect serve as the 'placeholder' for the clip region (this has advantages because you can use Fabric to move the object around and thus the clip region.
Please note that my solution uses the Lo-Dash utility library, particularly for _.bind() (see code for context).
Example Fiddle
Breakdown
1. Initialize Fabric
First, we want our canvas, of course:
var canvas = new fabric.Canvas('c');
2. Clip Region
var clipRect1 = new fabric.Rect({
originX: 'left',
originY: 'top',
left: 180,
top: 10,
width: 200,
height: 200,
fill: 'none',
stroke: 'black',
strokeWidth: 2,
selectable: false
});
We give these Rect objects a name property, clipFor, so the clipTo functions can find the one by which they want to be clipped:
clipRect1.set({
clipFor: 'pug'
});
canvas.add(clipRect1);
There doesn't have to be an actual object for the clip region, but it makes it easier to manage, as you're able to move it around using Fabric.
3. Clipping Function
We define the function which will be used by the images' clipTo properties separately to avoid code duplication:
Since the angle property of the Image object is stored in degrees, we'll use this to convert it to radians.
function degToRad(degrees) {
return degrees * (Math.PI / 180);
}
findByClipName() is a convenience function, which is using Lo-Dash, to find the with the clipFor property for the Image object to be clipped (for example, in the image below, name will be 'pug'):
function findByClipName(name) {
return _(canvas.getObjects()).where({
clipFor: name
}).first()
}
And this is the part that does the work:
var clipByName = function (ctx) {
var clipRect = findByClipName(this.clipName);
var scaleXTo1 = (1 / this.scaleX);
var scaleYTo1 = (1 / this.scaleY);
ctx.save();
ctx.translate(0,0);
ctx.rotate(degToRad(this.angle * -1));
ctx.scale(scaleXTo1, scaleYTo1);
ctx.beginPath();
ctx.rect(
clipRect.left - this.left,
clipRect.top - this.top,
clipRect.width,
clipRect.height
);
ctx.closePath();
ctx.restore();
}
NOTE: See below for an explanation of the use of this in the function above.
4. fabric.Image object using clipByName()
Finally, the image can be instantiated and made to use the clipByName function like this:
var pugImg = new Image();
pugImg.onload = function (img) {
var pug = new fabric.Image(pugImg, {
angle: 45,
width: 500,
height: 500,
left: 230,
top: 170,
scaleX: 0.3,
scaleY: 0.3,
clipName: 'pug',
clipTo: function(ctx) {
return _.bind(clipByName, pug)(ctx)
}
});
canvas.add(pug);
};
pugImg.src = 'https://fabricjs.com/lib/pug.jpg';
What does _.bind() do?
Note that the reference is wrapped in the _.bind() function.
I'm using _.bind() for the following two reasons:
We need to pass a reference Image object to clipByName()
The clipTo property is passed the canvas context, not the object.
Basically, _.bind() lets you create a version of the function that uses the object you specify as the this context.
Sources
https://lodash.com/docs#bind
https://fabricjs.com/docs/fabric.Object.html#clipTo
https://html5.litten.com/understanding-save-and-restore-for-the-canvas-context/
I have tweaked the solution by #natchiketa as the positioning of the clip region was not positioning correctly and was all wonky upon rotation. But all seems to be good now. Check out this modified fiddle:
https://jsfiddle.net/PromInc/ZxYCP/
The only real changes were made in the clibByName function of step 3 of the code provided by #natchiketa. This is the updated function:
var clipByName = function (ctx) {
this.setCoords();
var clipRect = findByClipName(this.clipName);
var scaleXTo1 = (1 / this.scaleX);
var scaleYTo1 = (1 / this.scaleY);
ctx.save();
var ctxLeft = -( this.width / 2 ) + clipRect.strokeWidth;
var ctxTop = -( this.height / 2 ) + clipRect.strokeWidth;
var ctxWidth = clipRect.width - clipRect.strokeWidth + 1;
var ctxHeight = clipRect.height - clipRect.strokeWidth + 1;
ctx.translate( ctxLeft, ctxTop );
ctx.rotate(degToRad(this.angle * -1));
ctx.scale(scaleXTo1, scaleYTo1);
ctx.beginPath();
ctx.rect(
clipRect.left - this.oCoords.tl.x,
clipRect.top - this.oCoords.tl.y,
ctxWidth,
ctxHeight
);
ctx.closePath();
ctx.restore();
}
Two minor catches I found:
Adding a stroke to the clipping object seems to throw things off by a few pixels. I tried to compensate for the positioning, but then upon rotation, it would add 2 pixels to the bottom and right sides. So, I've opted to just remove it completely.
Once in a while when you rotate the image, it will end up with a 1px spacing on random sides in the clipping.
Update to #Promlnc answer.
You need to replace the order of context transformations in order to perform proper clipping.
translation
scaling
rotation
Otherwise, you will get wrongly clipped object - when you scale without keeping aspect ratio (changing only one dimension).
Code (69-72):
ctx.translate( ctxLeft, ctxTop );
ctx.rotate(degToRad(this.angle * -1));
ctx.scale(scaleXTo1, scaleYTo1);
Replace to:
ctx.translate( ctxLeft, ctxTop );
ctx.scale(scaleXTo1, scaleYTo1);
ctx.rotate(degToRad(this.angle * -1));
See this:
https://jsfiddle.net/ZxYCP/185/
Proper result:
UPDATE 1:
I have developed a feature to clip by polygon:
https://jsfiddle.net/ZxYCP/198/
This can be done much more easily. Fabric provides render method to clip by the context of another object.
Checkout this fiddle. I saw this on a comment here.
obj.clipTo = function(ctx) {
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
clippingRect.render(ctx);
ctx.restore();
};
As I tested all fiddles above they have one bug. It is when you will flip X and Y values together, clipping boundaries will be wrong. Also, in order not doing all calculations for placing images into the right position, you need to specify originX='center' and originY='center' for them.
Here is a clipping function update to original code from #natchiketa
var clipByName = function (ctx) {
var clipRect = findByClipName(this.clipName);
var scaleXTo1 = (1 / this.scaleX);
var scaleYTo1 = (1 / this.scaleY);
ctx.save();
ctx.translate(0,0);
//logic for correct scaling
if (this.getFlipY() && !this.getFlipX()){
ctx.scale(scaleXTo1, -scaleYTo1);
} else if (this.getFlipX() && !this.getFlipY()){
ctx.scale(-scaleXTo1, scaleYTo1);
} else if (this.getFlipX() && this.getFlipY()){
ctx.scale(-scaleXTo1, -scaleYTo1);
} else {
ctx.scale(scaleXTo1, scaleYTo1);
}
//IMPORTANT!!! do rotation after scaling
ctx.rotate(degToRad(this.angle * -1));
ctx.beginPath();
ctx.rect(
clipRect.left - this.left,
clipRect.top - this.top,
clipRect.width,
clipRect.height
);
ctx.closePath();
ctx.restore();
}
Please check the updated fiddle
With the latest update on fabric 1.6.0-rc.1, you are able to skew the image by hold shift and drag the middle axis.
I have trouble with how to reverse the skew so that the clipping area stays the same. I have tried the following code to try to reverse it back, but didn't work.
var skewXReverse = - this.skewX;
var skewYReverse = - this.skewY;
ctx.translate( ctxLeft, ctxTop );
ctx.scale(scaleXTo1, scaleYTo1);
ctx.transform(1, skewXReverse, skewYReverse, 1, 0, 0);
ctx.rotate(degToRad(this.angle * -1));
Demo: https://jsfiddle.net/uimos/bntepzLL/5/
Update to previous guys answers.
ctx.rect(
clipRect.oCoords.tl.x - this.oCoords.tl.x - clipRect.strokeWidth,
clipRect.oCoords.tl.y - this.oCoords.tl.y - clipRect.strokeWidth,
clipRect.oCoords.tr.x - clipRect.oCoords.tl.x,
clipRect.oCoords.bl.y - clipRect.oCoords.tl.y
);
Now we are able to scale the clipping area without a doubt.

Resources