How do I fix this image (pixel by pixel) distortion issue? - javascript

I am attempting to distort an image displayed within a canvas, so it looks like a "planet". However I am struggling to find away to deal with a distortion issue. The only solution coming to mind is to find a way to reduce the radiusDistance variable, the bigger it is. That said, I am unsure how to achieve this. Any suggestions?
Below is the math and objects I am currently using to achieve this:
polarArray = [];
var polar = function(a,r,c){ //polar object, similar to pixel object.
this.a = a; //angle
this.r = r; //radius (distance)
this.color = c; //color, stored using an object containg r,g,b,a variables
};
loopAllPixels(function(loop){//loop through every pixel, stored in a pixel array
var pixel = loop.pixel;
/*each pixel object is structured like this:
pixel {
x,
y,
color {
r,
g,
b,
a
}
}
*/
var angle = pixel.x/360*Math.PI;
var radiusDistance = pixel.y/Math.PI;
polarArray.push(new polar(angle,radiusDistance,pixel.color));//store polar coordinate pixel + colour.
pixel.color = new colorRGBA(255,255,255,255);//set background as white.
});
for (var i=0;i<polarArray.length;i++){//loop through polarArray (polar coordinate pixels + colour)
var p = polarArray[i]; //polar pixel
var x = (p.r*Math.cos(p.a))+(canvas.width/2); //x coordinate
var y = (p.r*Math.sin(p.a))+(canvas.height/2); //y coordinate
if (setpixel(x,y,p.color)==true){ //set pixel at location.
continue;
}
break;
}
updatePixelsToContext();//draw to canvas
And here is the effect it currently produces (note that I flip the image horizontally before applying it to the canvas, and in this example, I set the background with a magenta kind of colour, for better clarity of the issue):
Note:
I am intending for the warping effect, just not the "ripping" of the pixels, caused by not obtaining all the neccessary pixel data required.
Also bear in mind that speed and effeciency isn't my priority here as of yet.

Related

How to make a hole in a polygon with CreateJs?

As you can see on attached image it has the rhombus with the ellipse inside which is almost transparent.
But this is just an image.
How can I create this with createjs?
A more detailed description of the problem:
What you see in the picture is not exactly what I need.
Ideally, my task is to make two triangles out of this rhombus with an ellipse inside.
The ellipse should create some kind of transparency in the triangle so that all the elements that will be under this triangle are visible through.
My implementation:
I make a triangle according to this example:
(thank to this fiddle)
(createjs.Graphics.Polygon = function(x, y, points) {
this.x = x;
this.y = y;
this.points = points;
}).prototype.exec = function(ctx) {
// Start at the end to simplify loop
var end = this.points[this.points.length - 1];
ctx.moveTo(end.x, end.y);
this.points.forEach(function(point) {
ctx.lineTo(point.x, point.y);
});
};
createjs.Graphics.prototype.drawPolygon = function(x, y, args) {
var points = [];
if (Array.isArray(args)) {
args.forEach(function(point) {
point = Array.isArray(point) ? {x:point[0], y:point[1]} : point;
points.push(point);
});
} else {
args = Array.prototype.slice.call(arguments).slice(2);
var px = null;
args.forEach(function(val) {
if (px === null) {
px = val;
} else {
points.push({x: px, y: val});
px = null;
}
});
}
return this.append(new createjs.Graphics.Polygon(x, y, points));
};
stage = new createjs.Stage("demoCanvas");
poly1 = new createjs.Shape();
poly1.graphics.beginFill("Red").drawPolygon(0,0,10,10,10,40,40,30,60,5,30,0);
poly1.x = 10;
poly1.y = 10;
stage.addChild(poly1);
stage.update();
(if there is a more convenient or even correct way to make a triangle and this will help in solving my problem, I will gladly accept your solution).
Next, I simply overlay the ellipse drawn with drawEllipse on top of this triangle.
I understand that I may be doing something wrong, and that is why I am here.
Any help will be accepted!
I assume you are using the Graphics API to draw your content. If so, you simply need to ensure the "hole" draws with reverse winding. This just means the shape needs to be drawn in the reverse direction.
For example, the Canvas2D rect method draws clockwise, so to subtract from them, the instructions need to be drawn in the other direction.
var s = new createjs.Shape();
s.graphics.beginFill("red")
.drawRect(0,0,300,300) // Draw a square
// Then draw a smaller square
.moveTo(100,100) // Top left
.lineTo(100,200) // Bottom left
.lineTo(200,200) // Bottom right
.lineTo(200,100) // Top right
.lineTo(100,100) // Top left
.closePath(); // Optional if you are done
The drawEllipse has an anticlockwise parameter which does the trick as well. Here is a jsfiddle sample, which actually draws it the other way (small cut-out first), but with the same result.
UPDATE
In order for the shape to "cut out" the other one, it has to be part of the same graphics instance, and part of the same path instructions. If you closePath() after any drawing instructions, any new instructions are drawn on top of that without cutting it out. Using separate shape instances does this automatically.
Using the updated code, I added a simple drawEllipse() call using default clockwise winding, and it cut out the circle: https://jsfiddle.net/lannymcnie/yd25h8se/ -- Note that I scaled up the coordinates from above x10 to make it more visible.
Cheers,

How can I avoid overlapping when creating sprites? JS - PHASER3

I'm new in this and I'm making a small game in JS, the problem that I have now is when I create enemies it sometimes overlaps, creating this:
The way that use to create them is simple,
resetShip(enemy_spaceship) {
enemy_spaceship.y = 0;
enemy_spaceship.x = Phaser.Math.Between(10,globalThis.config.width);
}
In X each sprite will have a random number from 10 to the width of the screen (canvas), the problem is that if a sprite has 440 in X and another one has 450 in X, those 10px aren't enough to separate them, some people told me to create a grid, but like I said I'm new and searching about grid can't find any example that I can use to this, thanks if you can help me :)
One option is for each enemy ship to be allocated a specific region in which it may start. If you have 2 ships, that means the first ship can be anywhere in the first half of the X axis, and the second ship can be anywhere in the second half of the X axis.
To do this, you should update your resetShip function to also take in a minX and maxX, and use that when defining it's location:
resetShip (enemy_spaceship, minX, maxX) {
enemy_spaceship.y = 0;
enemy_spaceship.x = Phaser.Math.Between(minX, maxX);
}
Then, you need to find a way to rest the group of ships, providing valid regions for each ship. Something like this:
resetEnemies(ships) {
//Each ship may be in a region that is 1/Nth of the width
let regionWidth = globalThis.config.width / ships.length
//We need to know the shipWidth so we don't let ships get too
//close to the left edge.
let shipWidth = 64
ships.forEach((ship, i) => {
//Assuming you just want padding on the left so it is no closer than 10px,
//this will define the minX for the Nth ship
const minX = Math.min(10, i*regionWidth)
//The maxX should not let a ship overlap the next region. So, we subtract the shipWidth
//to ensure that, at worst, it is right next to the next ship
const maxX = (i+1)*regionWidth-shipWidth
//Use the updated restShip to put it in a valid location for it's region
resetShip(ship, minX, maxX)
})
}

Matter.js calculating force needed

Im trying to apply a force to an object. To get it to move in the angle that my mouseposition is generating relative to the object.
I have the angle
targetAngle = Matter.Vector.angle(myBody.pos, mouse.position);
Now I need to apply a force, to get the body to move along that angle.
What do I put in the values below for the applyForce method?
// applyForce(body, position, force)
Body.applyForce(myBody, {
x : ??, y : ??
},{
x:??, y: ?? // how do I derive this force??
});
What do I put in the x and y values here to get the body to move along the angle between the mouse and the body.
To apply a force to move your object in that direction you need to take the sine and cosine of the angle in radians. You'll want to just pass the object's position as the first vector to not apply torque (rotation).
var targetAngle = Matter.Vector.angle(myBody.pos, mouse.position);
var force = 10;
Body.applyForce(myBody, myBody.position, {
x: cos(targetAngle) * force,
y: sin(targetAngle) * force
});
Also if you need it, the docs on applyForce() are here.
(I understand this question is old, I'm more or less doing this for anyone who stumbles across it)
You can rely on the Matter.Vector module and use it to substract, normalize and multiply positions vectors:
var force = 10;
var deltaVector = Matter.Vector.sub(mouse.position, myBody.position);
var normalizedDelta = Matter.Vector.normalise(deltaVector);
var forceVector = Matter.Vector.mult(normalizedDelta, force);
Body.applyForce(myBody, myBody.position, forceVector);

HTML5 : getImageData with onmousemove make slow my application in Firefox

I create a little html5 game with canvas.
In the canvas, there are many displayed sprites and one of them move automatically from left to right. The others are statics.
When I move the mouse onto the canvas, I draw all sprites in a temporary canvas and I use getImageData to find the sprite onto which the mouse is over.
But getImageData make slow anormally the moving sprite in Firefox.
So what is the solution to avoid this deceleration ?
Here my code :
function getSelectedObject(array_objects)
{
//Clear the temporary canvas :
tmpcx.clearRect(0, 0, tmpc.width, tmpc.height);
/*Search the right sprite object :*/
for(var i = array_objects.length-1; i >= 0; i--)
{
array_objects[i].draw(tmpcx);
imageData = tmpcx.getImageData(mouse_x, mouse_y, 1, 1);
component = imageData.data;
if(component[3] > 0)
{
//Return the sprite object found :
return array_objects[i];
}
else
{
tmpcx.clearRect(0, 0, tmpc.width, tmpc.height);
}
}
return false;
}
canvas.onmousemove = function(event)
{
selectedObject = getSelectedObject(array_objects);
}
Not sure how much of a performance gain you'd get with this - no need to clear the temp canvas between sprites .... the pixel is clear until a sprite is painted on it!
I've referenced a function called checkBoundingBoxisOver - not sure if you could write this function, but I can't right now - besides, I don't even know what your array_objects are!!!
I would think it were simple, just need the x, y, width, height of a sprite to do a preliminary check if the sprite could even possibly be under the mouse before doing the expensive draw
function getSelectedObject(array_objects) {
//Clear the temporary canvas :
tmpcx.clearRect(0, 0, tmpc.width, tmpc.height);
var sprite;
/*Search the right sprite object :*/
for (var i = array_objects.length - 1; i >= 0; i--) {
sprite = array_objects[i];
if (checkBoundingBoxisOver(sprite, mouse_x, mouse_y)) {
sprite.draw(tmpcx);
imageData = tmpcx.getImageData(mouse_x, mouse_y, 1, 1);
component = imageData.data;
if (component[3] > 0) {
return sprite;
}
}
}
return false;
}
I ran into a similar issue reading pixels from a large bitmap every frame of the animation. In my case it is a black and white image showing where the world is water or land.
getImageData is extremely slow on Firefox even when reading just a single pixel.
My solution is to call getImageData only once and store the result in a imageData variable
var imageData = self.context.getImageData(0,0,image.width, image.height);
Then you can make repeated calls to the image data and pull out the part of the image you want. In my case I just need a single pixel or a single color which looks like this
var pixelRed = this.imageData.data[(y* imageWidth * 4) + (x * 4)] == 0;
x and y are self explanatory and since the pixels are 4 byte values (Red, Green, Blue, Alpha) I need to multiply my array index by 4. It proves to be very fast for me.
It be pretty easy to use this code to grab any portion out of the array directly as long as it is not too big.

JS Canvas Collision-Detection using getImageData

As a very inexperienced programmer, I'm trying to code a game that detects when the player collides with certain colors on the canvas. I have a black square with coordinates "player.x" and "player.y" and dimensions 50x50 that moves around when you press the arrow keys. I also have a stationary red (255,0,0) square elsewhere on the canvas.
The function below is supposed to grab a slightly larger square around the "player" square and find out if there's any red in it. If there is, it will send up an alert. The problem is, this doesn't seem to be working.
function collideTest(){
var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");
var whatColor = c.getImageData(player.x - 5, player.y - 5,60,60);
for (var i = 0; i < 3600; i++) {
if (whatColor.data[i] == 255) {
alert("red");
}
}
}
I'm semi-aware that this is not the most efficient way to detect red pixels, but I wanted to simplify the code before posting it here. Is there something obviously wrong with the function?
The problem could lie in the way the function is called. It gets called at the end of another function that detects user-input and changes the coordinates of the "player" square. THAT function gets called right before everything is drawn on the canvas.
Thanks in advance for any help!
var whatColor = c.getImageData(player.x - 5, player.y - 5,60,60);
player.x and player.y must not be decimal, make sure they are rounded or getImageData will be angry and not play nice.
For each single pixel on the canvas, the whatColor.data array holds 4 sequential pieces of color information: red,green,blue,alpha(opacity). So the whatColor.data looks like this for each pixel:
whatColor.data[i] is the red component of the color.
whatColor.data[i+1] is the green component of the color.
whatColor.data[i+2] is the blue component of the color.
whatColor.data[i+3] is the alpha(opacity) component of the color.
So your iteration would look like this (4 indexes per pixel):
for(var i = 0, n = whatColor.data.length; i < n; i += 4) {
var red = whatColor.data[i];
var green = whatColor.data[i + 1];
var blue = whatColor.data[i + 2];
var alpha = whatColor.data[i + 3];
if(red==255){ ... it's a hit, do your thing! ... }
}
See here for a mini-tutorial on the imageData.data array: http://www.html5canvastutorials.com/advanced/html5-canvas-get-image-data-tutorial/
By the way, you might look at one of the canvas libraries that simplify game making with canvas. Here are just a few: easelJs, KineticJs, FabricJs, and more!

Categories