I want to use one shape (for instance a rectangle) to act as a mask or clipping path for another shape (for instance a circle, or line) in P5.js
I can see solutions for using images as masks, but not shapes. It seems mask() is not a function of shapes:
https://p5js.org/reference/#/p5.Image/mask
yes, you can.
create an extra rendering context with createGraphics().
In the draw loop draw something to this context which will be your
mask. Whatever should be visible in your result has to be colored
with the alpha channel, for example fill('rgba(0, 0, 0, 1)'.
Apply the mask to your original image myImage.mask(circleMask).
Your original image has now been modified by the mask, render it on
the screen: image(myImage, x, y, w, h)
Here is a working code example:
let circleMask;
let myImage;
function setup() {
createCanvas(400, 400);
circleMask = createGraphics(128, 128);
myImage = loadImage('FzFH41IucIY.jpg');
}
function draw() {
background(255);
circleMask.fill('rgba(0, 0, 0, 1)');
circleMask.circle(64, 64, 128);
myImage.mask(circleMask);
image(myImage, 200 - 64, 200 - 64, 128, 128);
}
There isn't a way to do this out of the box with P5.js.
Right now your question is more of a math question than it is a P5.js question. I'd recommend searching for something like "circle rectangle intersection" for a ton of results, including this one: Circle-Rectangle collision detection (intersection)
Depending on what you want to do, you could get away with drawing the shapes to images and then using those images as a mask. But more likely you're going to have to calculate the intersection yourself. You might be able to find a library that does this for you, but again, there isn't a simple out of the box way with P5.js.
Related
For neuroscience research I'm attempting to train rats to press shapes on a touch screen. Ideally, these shapes would be highly distinct polygons or blobs to make it easier for the rats to discriminate. However, to limit some biases toward certain shapes, I'd like to keep the area of each shape equivalent. I've been trying to achieve this on p5.js, but I'm very new to this.
The code I've got so far provides some of the shape randomness, but not the consitency in area:
function setup() {
createCanvas(500, 500);
background(255);
fill(0);
translate(width/2, height/2);
beginShape();
for(let i = 0; i < 5; i++) {
const x = random(-250, 250);
const y = random(-250, 250);
vertex(x, y);
endShape();
}
}
Any help achieving this would be very appreciated
Maybe it's not what you need, the shapes are all inscribed in a circle(edit:the second code ones), not a bounding box as I said earlier.
Both examples are online at p5js editor:
The code I had was more free form, it will eternally increase the number of sides:
about 20 sides:
about 130 sides
But at the begining its more what I think you need
the code is here:
https://editor.p5js.org/v-k-/sketches/siYtDw423
And...
I made a tweeked version to try to go closer to what I think you want :)
The code is here:
https://editor.p5js.org/v-k-/sketches/oMsWC2NHv
Perhaps you can play with the numbers to get What you need. For instance:
You can set the number of sides, or even reject sides smaller than something.
It's very simple stuff ;) Easy to tweek.
Have fun, hope the rats like it.
I am trying to highlight an Area that gets intersected by 2 Circle:
Example 1.:
The Yellow dots get, for testing purposes, random values. Those are used to draw a circle around, as well as to store an ellipse in the Background. In the Case of no intersection, the GUI acts correctly and display this:
After the random Values, the Shapes intersect. As I cannot seem to be able to add the new Shape made trough .intersect(), I just did a quick sp.setContent(), and got this image:
This basicly shows me the intersected space and colors it blue.
Everything is drawn on a Canvas, which basicly does the following:
Canvas canvas = new Canvas(250, 250);
....
gc = canvas.getGraphicsContext2D();
canvas.setHeight(imgTemp.getHeight());
canvas.setWidth(imgTemp.getWidth());
gc.drawImage(imgTemp, 0, 0);
Aswell as with some other Loops to draw the shapes and the circles.
Now, the code for the intersect is the following:
if (!(e.equals(eT))) {
if (e.getBoundsInParent().intersects(eT.getBoundsInParent())) {
System.out.println("Collision detected!");
Shape inter = Shape.intersect(e, eT);
if(inter.getBoundsInLocal().getWidth() > 0 && 0 < inter.getBoundsInLocal().getHeight()){
inter.setFill(BLUE);
inter.setStrokeWidth(3);
sp.setContent(inter);
}
}
I'm not that used to JavaFX and have only begun really working on it this Weekend for a small Project, but I am guessing that I might need to change from canvas to something else to make use of the shapes? Or is there a way to "tranform" the Shape of the intersect into something drawable by GraphicsContext2D?
Why don't you just put your Canvas into a Group and then add your shapes to the same Group. Why would you insist on drawing everything into the Canvas? A Canvas is just a Node like all the other Shapes and you can mix them freely in the SceneGraph.
Another question would be why you are using the Canvas at all if you have already realized that this leads to problems in your case.
I'm trying to draw an icon(.png) inside a QWidget with QPainter::drawPixmap()
:
QPixmap _source = "/.../.png";
painter.setRenderHint(QPainter::HighQualityAntialiasing);
painter.drawPixmap(rect(), _source);
but in comparing to QLabel (for example) and in lower size (19*19 in my case) the result isn't perfect.
What can I do?
****Edit****
QLabel with pixmap # size 19*19:
My painting # size 19*19 via SmoothPixmapTransform render type:
You are setting the wrong render hint, you need QPainter::SmoothPixmapTransform to get smooth resizing. By default the nearest neighbor method is used, which is fast but has very low quality and pixelates the result.
QPainter::HighQualityAntialiasing is for when drawing lines and filling paths and such, i.e. when rasterizing geometry, it has no effect on drawing raster graphics.
EDIT: It seems there is only so much SmoothPixmapTransform can do, and when the end result is so tiny, it isn't much:
QPainter p(this);
QPixmap img("e://img.png");
p.drawPixmap(QRect(50, 0, 50, 50), img);
p.setRenderHint(QPainter::SmoothPixmapTransform);
p.drawPixmap(QRect(0, 0, 50, 50), img);
img = img.scaled(50, 50, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
p.drawPixmap(100, 0, img);
This code produces the following result:
There is barely any difference between the second and third image, manually scaling the source image to the desired dimensions and drawing it produces the best result. This is certainly not right, it is expected from SmoothTransformation to produce the same result, but for some reason its scaling is inferior to the scale() method of QPixmap.
I am currently working on generating "heat-maps" with QPainter and QImage. My method consists of drawing multiple circles with black to transparent QRadialGradients as the QBrush (see "Intensity Map"). Then I apply a gradient map to the intensity map to get the desired "heat-map" effect (see "After Gradient Map").
The issue I am having, which is more apparent in the "After Gradient Map" image, is that the circles are not blending correctly. Where circles overlap do seem to partially blend, but towards the edges you can clearly see where the circles end (almost a outer-glow). I would like an effect which has no visible borders between the circles and blends correctly.
Intensity Map
After Gradient Map (different intensity map)
Code
// Setup QImage and QPainter
QImage *map = new QImage(500, 500, QImage::Format_ARGB32);
map->fill(QColor(255, 255, 255, 255));
QPainter paint(map);
paint.setRenderHint(QPainter::HighQualityAntialiasing);
// Create Intensity map
std::vector<int> record = disp_data[idx]; // Data
for(int j = 1, c = record.size(); j < c; ++j) {
int dm = 150 + record[j] * 100 / 255; // Vary the diameter
QPen g_pen(QColor(0, 0, 0, 0));
g_pen.setWidth(0);
QRadialGradient grad(sensors[j-1].x, sensors[j-1].y, dm/2); // Create Gradient
grad.setColorAt(0, QColor(0, 0, 0, record[j])); // Black, varying alpha
grad.setColorAt(1, QColor(0, 0, 0, 0)); // Black, completely transparent
QBrush g_brush(grad); // Gradient QBrush
paint.setPen(g_pen);
paint.setBrush(g_brush);
paint.drawEllipse(sensors[j-1].x-dm/2, sensors[j-1].y-dm/2, dm, dm); // Draw circle
}
// Convert to heat map
for(int i = 0; i < 500; ++i) {
for(int j = 0; j < 500; ++j) {
int b = qGray(map->pixel(i, j));
map->setPixel(i, j, grad_map->pixel(b, 0)); //grad_map is a QImage gradient map
}
}
As you can see, there is no QPen for the circles. I have been trying a variety of blending modes with no success. I have also changed the rendering hint to HighQualityAntialiasing. I have also tried making the circles much larger than the radial gradient, so there is no way the gradient is cut-off or a border is applied to the outside of the circle.
Any ideas? Thanks!
I think this is a form of mach-banding, which is an optical illusion where changes in luminance are enhanced by the visual system, causing the appearance of bright or dark bands which are not actually present in the image. Typically these are seen on the boundary between two distinct areas, but in the case here I believe it is the sharp discontinuity in the gradients being observed.
Here are some images to demonstrate the issue:
This first image is calculated in software, and consists of three circles each drawn with a radial linear gradient. Mach-band effects should be visible at the edges of the overlap between circles, as these are the points where the gradient sharply changes.
This second image is exactly the same calculation, but instead of being linear along the radius, the gradient is mapped to a curve (I used the first hermite basis function). The bands should almost entirely have disappeared:
As to why this affects a colourised image more, I'm not sure it does. I think in the case above, perhaps there is additional banding caused by the colourisation effectively being a palette lookup, resulting in additional banding.
I performed roughly the same colourisation locally, also simply mapping a palette, and the effect is similar:
Fixing this using QT's linear gradients is probably non-trivial (you could try adding a lot more control points to the gradient, but you'll have to add quite a few...), but calculating such an image in software is not hard. You could also consider some other post-processing effects, such as adding a blur, and/or adding noise. Anything breaking the discontinuity in the gradient would likely help.
I agree with JasonD.
Furthermore, please keep in mind that Qt is doing linear blending in sRGB color space, which is not linear (it has a gamma 2.2 applied).
To do this right, you need to do the blending or interpolation in linear light, then convert to sRGB (apply gamma) for display.
So basically when I try to draw more a mesh inside an FBX file its orientation is always removed and it's scaled down. I'm not sure if the issue is caused by code or the way I'm exporting the FBX files. I have been trying to narrow down the cause and I am fairly sure it's not caused by the way I export the FBX (but I could be wrong), so it's either the XNA content pipeline or my drawing code
Here are some pics I took to show my problem, where the gray background is in 3Ds Max as I see it and red background is in XNA:
THis is as it appears in 3D StudioMax: http://i.stack.imgur.com/e0oW4.png
This is how it appears in XNA: http://i.stack.imgur.com/1vOcx.png
Both are being viewed from the same angle and direction but varying distances.
Now what is really odd is if I create another mesh in max, say a box, and export that (along with the original model), it works fine: http://i.stack.imgur.com/SIDg9.png
So long as there is more than one mesh in the fbx model it draws properly (though I'm still suspicious if it's drawing with proper scaling applied, i.e. if in Max it is 1 unit long in XNA it becomes something like 1.27 units long), if there is less its orientation which I applied to it in 3D studio max is removed when I draw it.
This is how I draw the model:
model.CopyAbsoluteBoneTransformsTo(boneTransforms);
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = boneTransforms[mesh.ParentBone.Index];
Vector3 cameraPosition = Camera.Get.Position;// new Vector3(0, 0, 0);
//cameraPosition.X = -Camera.Get.PosX;
//cameraPosition.Y = Camera.Get.PosY;
effect.View = Camera.Get.View;// Matrix.CreateLookAt(cameraPosition, cameraPosition + Camera.Get.LookDir, Camera.Get.Up);
effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
BaseGame.Get.GraphicsDevice.Viewport.AspectRatio,
0.01f, 1000000); //Matrix.CreateOrthographic(800 / 1, 480 / 1, 0, 1000000);
//effect.TextureEnabled = true;
effect.LightingEnabled = true;
effect.PreferPerPixelLighting = true;
//effect.SpecularColor = new Vector3(1, 0, 0);
}
mesh.Draw();
}
Obviously mesh.draw() is called twice when there is more than one mesh in the fbx file..
Generally if you are having a problem with the position or scale of the mesh while rendering, then it's likely to be related to the matrices. Not necessarily the exporting, but rather how you use them in the code.
I use blender3d for modelling, but I know that Blender3d actually defines different spaces when you are creating the meshes within the editor. For example, if you create a mesh while in 'object' mode, the position/rotation/scale of the object in the scene will not be exported (because that object will be the root of a new tree, centered around 0,0,0). So I would check for a similar situation in 3DMax - make sure you are transforming the vertices in Max relative to 0,0,0, or else you may lose the 'initial' translation and when you render in XNA, all the objects will be rendered around your 0,0,0 (i.e. appear mixed together).
Failing that, and I can't remember exactly off the top of my head, but I think you may need to multiply the current mesh's absolute matrix transform with that of the parent's world matrix transform. Although it's been a while so I'm not too sure.