Simulate ECG with JS & Canvas - javascript

I am trying to simulate a constant heartbeat with JS and Canvas. I have figured most of it out, but my problem is that the line always starts at a different Y position and therefore when I try to clean up the path it looks a little off. I have a JS here, it's one that I modified from another post.
The answer should either be in modifying the PY coordinate somewhere but I can't figure out where. Or in the following line in the loop function.
ctx.clearRect(px,0, scanBarWidth, h);
Please let me know if you can help me with this. Thanks.
https://jsfiddle.net/tFn66/138/

Check the source code of this solution. It using a canvas as a backend of draw
document.body.innerHTML += '<ecg-line></ecg-line>';
ecgLine((bang) => setInterval(() => bang(), 1000));

Related

Connect 2 svg elements

There has been a lot of questions regarding the coördinate system of svg elements but no one has got me solving my problem.
Look at this fiddle:
https://jsfiddle.net/archemedia/4f54jnm8/
In the startup function, I added connect("A", "B") which connects element A and B with the line.
When I try to connect("A", "D") the line doesn't position correctly, due to the transform attribute of element D.
Could someone provide me with a clear solution?
I don't want to use a svg library, I just want plain javascript code which solves the problem, preferably by adding it to the fiddle.
Many thanks
Your getMid function needs to account for the transform matrix of the rectangles.
function getMid (rect, svg) {
let point = svg.createSVGPoint();
point.x = rect.x.baseVal.value + rect.width.baseVal.value / 2;
point.y = rect.y.baseVal.value + rect.height.baseVal.value / 2;
return point.matrixTransform(svg.getScreenCTM().inverse().multiply(rect.getScreenCTM()));
}
Note the new svg parameter. This is your SVGSVGElement. In the fiddle, you can grab it with document.getElementById('Laag_1').
Normally, I'd cite the relevant pages on MDN, but their SVG documentation is lacking. I had to piece this together from a couple of SO questions. The key was searching "svg get transform matrix" and following the rabbit hole from there.
This is by far the most correct and useful answer and it might server the community. I've searched a lot and got multiple workarounds with regex and custom functions, all of which didn't work. My problem is finally solved.
I updated the fiddle with the answer from AuxTaco and the getCTM() tweak suggested by jcaron. Thanks everyone!
function getMid(rect, svg){
var point = svg.createSVGPoint();
point.x = rect.x.baseVal.value + rect.width.baseVal.value / 2;
point.y = rect.y.baseVal.value + rect.height.baseVal.value / 2;
return point.matrixTransform(svg.getCTM().inverse().multiply(rect.getCTM()));
}
https://jsfiddle.net/archemedia/4f54jnm8/2/

Collision detection using a collision array inside html5 canvas

I am trying to detect if a character and an object inside an image collide. I am using a function that can parse the image and creates a collision array and another function that can detect if there is a collision or not in a specific location. My problem is that the isCollision function is never executed that's my jsfiddle : http://jsfiddle.net/AbdiasSoftware/UNWWq/1/
if (isCollision(character.x, character.y)) {
alert("Collision");
}
Please help me to fix my problem.
Add this in the top of your init() method and it should work:
FieldImg.crossOrigin = '';
As you are loading the image from a different origin CORS kicks in and you need to request cross-origin usage when using getImageData() (or toDataURL()).
See modified fiddle here.
Note: in you final code this is probably not gonna be necessary though as you probably want to include the images in the same domain as the page itself - in these cases you need to remove the cross-origin request unless your server is setup to handle this. Just something to have in mind for later if what worked suddenly don't...
Ok i found it :
You are loading a huge background image, and you draw part of it on a much smaller canvas.
You do visual collision detection using a binary view on the display canvas that you build in the process() function.
The issue comes when you want to test : to compute the pixel position of the player within the binary view, you are using y*width + x, but with the wrong width, that of the background image when it should be that of the view (cw).
function isCollision(x, y) {
return (buffer8[y * cw + x] === 1);
}
.
move right and look in the console with this fiddle :
http://jsfiddle.net/gamealchemist/UNWWq/9/

Detecting irregular Shape

Leading up from this question Detecting mouse coordinates with precision, I have learnt quite a bit in the past few days. Here are what I picked as best learning resources on this topic:
http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space/
http://www.gamedev.net/page/resources/_/technical/graphics-programming-and-theory/quadtrees-r1303
http://jsfiddle.net/2dchA/2/
The code in (3) works in JSFiddle but breaks at this section in my testing environment (VS2012):
var myTree = new Quadtree({
x: 0,
y: 0,
width: 400,
height: 300
});
with the message Quadtree is undefined in IE. FF & Chrome just gloss over it and display an empty page. I couldn't sort it out. Question 1: Can someone help out with that?
My main question:
I have a region (parcels of land like a map) with about 1500 parcels drawn in html5, not jpg or png images. It is a lot of lines of code to complete that but the rendering is great, so I am keeping it that way. I intend to have a mouseover event tell me which parcel I am standing on when the mouse stops. As you will see in the previous question referred my previous attempts were not impressive. Based on the learning I have been doing, and thanks to Ken J's answer/comments, I would like to go with this new approach of slicing up my canvas into say 15 quads of 100 objects each. However, I would like some guidance before I take another wild dive the wrong way.
Question 2: Should I slice it up at creation or should the slicing happen when the mouse is over a region, ie, trail the mouse? The latter sounds better to me but I think I can do with some advice and, if possible, some start out code. The quadtree concept is completely new to me. Thanks.
Can't help with question 1.
You should definitely build the tree as early as possible, given that the objective is to get the page to respond as quick as possible once the user clicks somewhere.
Keep the tree for as long as the user interacts with the 2d area. Updating a quad tree shouldn't be too hard, so even if the area changes contents, you should be able to reuse the existing tree (just update it).
Given the fact that your draw area is well know i see no advantage in a QuadTree over a spacial hash function. This function will give you an integer out of an (x,y) point.
var blocWidth = 20;
var blocHeight = 20;
var blocsPerLine = ( 0 | ( worldWidth / blocWidth) ) + 1 ;
function hashPoint(x,y) {
return ( 0 | (x/blocWidth)) + blocsPerLine*(0|(y/blocHeight));
}
once you built that, hash all your parcels within an array :
parcelHash = [];
function addHash(i,p) {
if (!parcelHash[i]) { parcelHash[i]=[ p ]; return; }
if (parcelHash[i].indexOf(p) != -1 ) return;
parcelHash[i].push(p);
}
function hashParcel (p) {
var thisHash = hashPoint(p.x,p.y); // upper left
addHash( thisHash, p);
thisHash = hashPoint(p.x+width, p.y); // upper right
addHash(thisHash, p);
thisHash = hashPoint(p.x, p.y+p.height); // lower left
addHash(thisHash, p);
thisHash = hashPoint(p.x+width, p.y+p.height); // lower right
addHash(thisHash, p);
};
for (var i=0; i<allParcels.length; i++) { hashParcel(allParcels[i]) };
now if you have a mouse position, you can retrieve all the parcels in the
same block with :
function getParcels(x,y) {
var thisHash = hashPoint(x,y);
return parcelHash[thisHash];
}
I'll just give you few tips in addition to what others have said.
... have a mouseover event tell me which parcel I am standing on ...
From your other messages I conclude that parcels will have irregular shapes. Quadtrees in general work with rectangles, so you'd have to calculate the bounding rectangle around the shape of the parcel and insert that rectangle in the quadtree. Then are when you want to determine whether mouse is over a parcel, you'll query the quadtree which will give you a set of parcels that might be under the mouse, but you'll have to then do a more precise check on your own to see if it indeed is.
... when the mouse stops.
From your other questions I saw that you try to detect when the mouse has "stopped". Maybe you should look at it this way: mouse cursor is never moving, it's teleporting around the screen from previous point to next. It's always stopped, never moving. This might seem a bit philosophical, but it'll keep your code simpler. You should definitely be able to achieve what you intended without any setTimeout checks.
... slicing up my canvas into say 15 quads of 100 objects each.
... Should I slice it up at creation or should the slicing happen when the mouse is over a region
You won't (and can't) do slicing, quadtree implementation does that automatically (that's its purpose) when you insert or remove items from it (note that moving the item is actually removing then re-inserting it).
I didn't look into the implementation of quadtree that you're using, but here are two MX-CIF quadtree implementations in case that one doesn't work out for you:
https://github.com/pdehn/jsQuad
https://github.com/bjornharrtell/jsts/tree/master/src/jsts/index/quadtree
The problem in question 1 probably happens because jsfiddle (http) page is trying access quadtree.js which is on https

Can somebody please help me with a geometric transformation problem?

I need to draw a circular arc between two given points. I also have the arc's radius. I understand that this can be done using standard canvas APIs but I need to handle the case of elliptical arcs too. This code is a generalized solution. The only problem right now is that it doesn't work!
The mathematical concept behind this code is at https://math.stackexchange.com/questions/53093/how-to-find-the-center-of-an-ellipse.
My JS code is implementation of that. My JS code can be found at http://jsfiddle.net/BkEnz/2/. Ideally both the circles there should pass through the two little pink dots.
I hope somebody can point me towards the right direction. I have been trying to solve this for past few days now!
Fixed this issue. The corrected working code is at http://jsfiddle.net/ZxRBT.
Notice the line
var t = translate(-R1R2x, -R1R2y, IDENTITY_TRANSFORM());
In my previous version of the code this line was
var t = translate(-R1R2x, -R1R2y, sr);
So when I was calculating the value of C1 and C2, using the following code
C1 = compose(vut, [[R1x],[R1y],[1]]);
C2 = compose(vut, [[R2x],[R2y],[1]]);
I was also applying the sr composition over R1x,R1y and R2x,R2y, but these points were already in sr coordinate.
This was a grave mistake which I overlooked for really a long time.

raphael question - using animateAlong

I am using raphael to do some SVG animation and cannot seem to get the function animateAlong to work. I continue to get the error "attrs[0] is undefined" referencing line 3450 of the un-compressed raphael code.
Basically, I create a circle with a given center and then want to animate an image around that path. Here is that simple code:
var circle = paper.circle(circleCenterX, circleCenterY, circleRadius);
I then clone an image (since I plan to have a number of these on this path) and place at the edge of the circle:
var wheelClone = wheel.clone();
var wheelRadius = parseInt(wheel8ImageWidth/2);
wheelClone
.translate((circleCenterX + circleRadius)-3, circleCenterY-wheelRadius);
where I init circleCenterX earlier with circleCenterX = circle.attr(cx);
This all works fine with image placed correctly - but it errors on animateAlong.
I have studied as many examples as i can find and have dissected the documentation but cannot get the hang here.
So, I simply try to call the function but have no earthly idea what the documentation is referring to. The documentation animates a dot around a path but refers to two variables - rx and ry which I cannot suss out - both in an init function and then with the callback.
Here is what I have - - where the rx and ry and just made up as I have no idea what they refer to.
var wheelAttr = {
rx: 5,
ry: 3
};
wheelClone.attr(wheelAttr).animateAlong(circle, 2000, true, function() {
wheel.attr({rx: 4, ry: 4});
});
My current jsFiddle is a bit of a mess at the moment and I can clean it up, but I suspect that there is some obvious thing here?
Thanks to all
S
I don't think a circle is actually a valid path (i.e, something you can pass to animateAlong()). I think you need to create a path that is circular. See the following:
svg-animation-along-path-with-raphael
Hopefully, it will help.

Categories

Resources