Pixelate animation - javascript

I'm trying to pixelate an animation.. I have a .png image where I cut in frames. I have a scrollbar who gives a number, which is the new size of every pixel. (rasterSize)
I already did it for an image and it's working.
http://bht-homework.com/RMA/PIX_PRES1/
But for animation it looks like doesn't calculate the first pixels.
http://bht-homework.com/RMA/PIX_PRES2/
var imgData=context.getImageData(0,0,img.width,img.height);// width is 190,height 240
for (var x = 0; x < spriteSizeWidth; x++) {
for (var y = 0; y < spriteSizeHeight; y++) {
var rasterX = ((x / rasterSize) | 0) * rasterSize;
var rasterY = ((y / rasterSize) | 0) * rasterSize;
var rasterValIndex = (rasterX + rasterY * imgData.width) * 4;
r=imgData.data[rasterValIndex];
g=imgData.data[rasterValIndex + 1];
b=imgData.data[rasterValIndex + 2];
a=imgData.data[rasterValIndex + 3];
context.fillStyle="rgba(" +r+","+g+","+b+","+a+")";
context.fillRect(x,y,rasterSize,rasterSize);
}
}
Does someone has an idea how to fix it?
Thanks!

Though it might look as it would skip the first few pixels of your image, it actually just draws the blocks at the wrong position. It's offset by rasterSize.
You need to shift back the pixels to the correct position.
So simply replace
context.fillRect(x, y, rasterSize, rasterSize);
by
context.fillRect(x - rasterSize, y - rasterSize, rasterSize, rasterSize);

Related

Make a Text Based FPS in Javascript [Solved]

Original Question
When I made the game in C++, the window and buffer size was 120 x 40 and the screen(array of wchar_t) was the same hence each character would take up equal space such that the whole array would make the screen and later redrawing it on the console
I am trying to make the basic console to work with the canvas but not every character has equal amount of space and not all would fit into it
//Display map
for (nx = 0; nx < MAP_WIDTH; nx++)
{
for (ny = 0; ny < MAP_HEIGHT; ny++)
{
Screen[(ny + 1) * SCREEN_WIDTH + nx] = MAP[ny * MAP_WIDTH + nx] //returns a character '#' or '.';
}
}
this is the sample of how I fill the array
`Screen = Array(SCREEN_WIDTH * SCREEEN_HEIGHT);`
this is the initialization of array
now how would I draw that screen buffer to the canvas
in C++ it would be like this
//finally printing the screen
screen[ScreenWidth * ScreenHeight - 1] = '\0';
WriteConsoleOutputCharacter(hConsole, screen, ScreenWidth * ScreenHeight, { 0, 0 }, &dwBytesWritten);
I just ditched the canvas and just printed my text inside a para tag with such
let line = "";
for (let y = 0; y < SCREEN_HEIGHT; y++)
{
for (let x = 0; x < SCREEN_WIDTH; x++)
{
line += screen[y * SCREEN_WIDTH + x];
}
line += "\n";
}
document.getElementById("consoletext").innerText = line;

Determining the of grid used by circle

I would like to determine the proportion of a grid cell occupied by one (or more) circles. So, for example, the top left grid cell below would have a small value (~0.1) and the center grid cell (7,7) would have a value of 1, as it is entirely occupied by the circle.
At present I am doing this with canvas.context2d.getImageData, by sampling the cell's content to determine what is present. This works but is way too slow. This is this method:
var boxRadius = 6;
var boxSize = boxRadius * 2 + 1;
var cellWidth = gridWidth / boxSize;
var cellHeight = gridHeight / boxSize;
var scanInterval = 10;
var scanCount = 10;
for (var x = viewcenterpoint.x - (gridWidth / 2); x <= viewcenterpoint.x + (gridWidth / 2) -1; x += cellWidth) {
for (var y = viewcenterpoint.y - (gridHeight / 2) ; y <= viewcenterpoint.y + (gridHeight / 2) -1; y += cellHeight) {
var cellthreatlevel = 0.0;
for (var cellx = x; cellx < x + cellWidth; cellx += scanInterval){
for (var celly = y; celly < y + cellHeight; celly += scanInterval){
var pixeldata = context.getImageData(cellx, celly, 1, 1).data;
cellthreatlevel += ((pixeldata[0] + pixeldata[1] + pixeldata[2])/765 * -1) + 1;//255; //grey tone
scancount += 1;
}
}
cellthreatlevel = cellthreatlevel / scanCount; //mean
}
}
The getImageData call is the source of the problem - it is way too slow.
Given that I have an array of circles, each with their x, y and radius how can I calculate this? If possible I would like each value to be a decimal fraction (between 0 and 1).
The grid is static, but the circles may move within it. I would be happy to get a rough estimate for the value, it doesnt need to be 100% accurate.
You can use the Monte Carlo Method to get an approximate solution. It is a probability based method, in which you generate random samples in order to estimate some value. In this case, given the coordinates of the circle center, the circle radius and the boundaries of the grid cell, you can estimate the proportion of the grid cell occupied by the circle by generating K random samples (all contained inside the grid cell), and verify the proportion of the samples that are also inside the circle. The more samples you generate, the more accurate your result will be.
Remember: to verify if a given sample P is inside a circle with center C and radius R, all you have to do is check if the equation sqrt((Px-Cx)^2 + (Py-Cy)^2) <= R is true
You only need to call getImageData once, to obtain the entire canvas.
Once you have the image data you can access the bytes at offset 4 * (celly * width + cellx) to get the RGB(A) data.
This should be massively faster since it only makes one call to the graphics hardware instead of 10s of thousands.

Point in Polygon falsely detected

Derived from this: How to tackle diagonally stacked, rounded image background element hovers?
I made imagemap areas and transformed them for my case, but, now there is a problem with point in polygon hit detection.
It appears that only the bottom right quadrant is always correct, but, only if looking outside the ring - inside the detection might be still be incorrect. Other quadrants, outside the ring, occasionally report a positive hit where it should be false.
Fiddle: http://jsfiddle.net/psycketom/9J4dx/1/
The red lines are drawn from the polygon that's generated from data-map.
The blue line represents the polygon we're currently checking.
The point in polygon function comes from: https://github.com/substack/point-in-polygon
var pointInPolygon = function(point, vs)
{
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var x = point[0], y = point[1];
var inside = false;
for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
var xi = vs[i][0], yi = vs[i][1];
var xj = vs[j][0], yj = vs[j][1];
var intersect = ((yi > y) != (yj > y))
&& (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
};
I cannot seem to understand what's the problem here.
Your mapToPolygon function doesn't convert the parsed points from string to number. Because of this, the pointInPolygon function ends up comparing the strings of the coordinates, not the actual coordinates. Using a parseInt on line 31 of the fiddle fixes the problem.
Create an off-screen canvas and use the context's .isPointInPath(x, y) function.
Loop through all of your polygons (in your example you would loop through them in reverse because you have smallest last. The smallest would be the highest level / greatest z-index).
On you get a hit (isPointInPath returns true) stop.
Something like...
var offcanvas = document.createElement("canvas");
...
var x = e.pageX - $ages.offset().left;
var y = e.pageY - $ages.offset().top;
revlayers.each(function() {
var $elm = $(this);
var poly = $elm.data("polygon");
var ctx = offcanvas.getContext("2d");
if(poly.length > 0) {
ctx.beginPath();
ctx.moveTo(poly[0][0], poly[0][1]);
for(var i=1; i<poly.length; i++) {
ctx.lineTo(poly[i][0], poly[i][1]);
}
if(ctx.isPointInPath(x, y)) {
hit.text($elm.attr("href"));
return false; // end the .each() loop
}
}
})

Draw a html5 canvas cylindre with camera view inside the cylinder

I think the title is self-explanatory.
I need to build html5 canvas cylindre with the camera view in the center of the cylinder.
On the wall of the cylinder i need to build something like pictures, the cylinder to rotate and zoom.
If anyone has some pointers as to where to start with the camera and the cylinder please help.
To help you understand my description i have posted a image
http://s21.postimg.org/fpnmukbef/inside_cilindre.jpg
i think you must work on the 2d picture and on last step transform the needed part
to transform the good part into 3d, i think you must stretch each colon depending on the parabola equation you choice
function getStretch(x,maxx)
{ /* here i choice :
f(x) = (x*x)+3 for top
f(x) = -(x*x)+1 for bottom
when y >= 0 and y <= 4
x >= -1 and x <= +1
*/
// convert x ~ maxx to -1 ~ 1
var ratio = 2/maxx; // -1 to 1 === 2
x = x * ratio;
x -= 1; // switch from 0 ~ 2 to -1 ~ 1
var sizeY = 4;
var y = -(x*x)+1; // bottom get y >= 0 and y <= 1 result, easier to compute
y *= 2; // double to add up and bottom
var colonHeight = sizeY - y;
var colonRatio = colonHeight / sizeY;
return colonRatio; // return the height ratio for this colon
}
values for a 101 colons view : http://jsfiddle.net/L9YgL/1/
var view_start_x = 200; // current view start at 200px from left source image
var view_size_x = 399; // current view work on 400 px width
// get our stretch ratio for each colon
var stretch_values = [];
for(var x=0;x<=view_size_x;x++) stretch_values[x] = getStretch(x,view_size_x);
// now we need a function to get the colon height and position
var colonHeight = 400; // height of source image, and max height of out
function getColonInfo(x)
{ if(x < 0 || x > view_size_x) return {h:42,y:0};
// compute current colon height
var ratio = stretch_values[x];
var height = parseInt( colonHeight * ratio ,10);
var posY = parseInt( (colonHeight - height)/2 ,10);
return {h:height,y:posY};
}
// save this info for each out colon
var colon_info = [];
for(var x=0;x<=view_size_x;x++) colon_info[x] = getColonInfo(x);
// now a function to render a colon with a zoom
function renderColon(x,sourceX)
{ var info = colon_info[x];
var originalHeight = colonHeight;
var height = info.h;
var y = info.y;
// now do your reduce/blit magic here
// render at "x","y" a colon with height of "height"
// from source colon "sourceX" who get height of "originalHeight"
}
// and a function to iterate each colon and do the magic
function my2dTo3d()
{
for(x=0; x<=view_size_x; x++)
{ var offset = x + view_start_x;
renderColon(x,offset);
}
}
ok there certainly be a better method to do this, here i do it at hand, maybe css3 ?

I am trying to plot coordinates around a square

I am trying to plot coordinates around a square programatically here it is hard coded to show what i am after.
http://jsfiddle.net/zwkny/
// amount of chairs
var aoc = 4;
// table width
var tw = 200;
// table height
var th = 200;
// chair width height
var cwh = 60 / 2;
var space = tw * 4 / aoc;
var left = [-30,100,-30,-160];
var top = [-160,-30,100,-30];
// straing point
var sp = 12;
for(var i=0; i<aoc; i++){
var x = cwh + space * i / aoc;
console.log(x);
//var y = space / 2 - cwh * i;
$("#center").append("<div class='chair' style='left:"+left[i]+"px;top:"+top[i]+"px;'>"+i+"</div>");
}
Maths is definately not my strong point just thought i would post up here see if anyone can help point me in the right direction i keep going and update if i get it???
I need it this way to represent people the small circles standing around the large square but there will be random amounts of people and they all need to be at equal distances.
I posted the same post about a circle object yesterday and now i am on squares i just cant get my head around the maths, any help.
Sore that this has been voted down just thought i would update with a post putting all these together
http://devsforrest.com/116/plot-positions-around-shapes-with-javascript
Hope it helps someone else
var x,y;
// amount of chairs
var totalChairs = 12;
// square size
var squareSize = 200;
var chairSize = 20;
for(var i=0; i<totalChairs; i++){
var angle = 2*Math.PI * i/totalChairs;
if (angle > Math.PI/4 && angle <= Math.PI* 3/4){
x = (squareSize/2) / Math.tan(angle);
y = -squareSize/2;
} else if (angle > Math.PI* 3/4 && angle <= Math.PI* 5/4){
x = -squareSize/2;
y = (squareSize/2) * Math.tan(angle);
} else if (angle > Math.PI* 5/4 && angle <= Math.PI* 7/4){
x = -(squareSize/2) / Math.tan(angle);
y = -squareSize/2 + squareSize;
} else {
x = -squareSize/2 + squareSize;
y = -(squareSize/2) * Math.tan(angle);
}
x -= chairSize/2;
y -= chairSize/2;
$("#center").append("<div class='chair' style='left:"+x+"px;top:"+y+"px;'></div>");
}
Demo

Categories