Using SVG with ajax to animate state of IO hardware - javascript

The company I'm working for is selling micro computers that can manage and monitor diffrent IO devices.
They are using ajax for the web IO stuff and I created a new graphic for a Voltmeter that contains 41 states from 0 Volt to 20 with 0,5 stepping.
My first question would be, if that is being called a sprite because there are so many images?
The code I wrote to load the images was already much shorter than the company's because I made a function to generate the img links via a counter.
var i = 1;
function counter()
{
var img = "http://"adress"/"+i.toString()+".png";
if (i == 40)
{
i=0;
}
i++;
document.getElementById('picture').src = img;
}
now the next step I was asked was doing that with a svg.
I could do the same thing with a svg of course, but I´ve read about being able to animate svg.
The first big question is:
Should I make a svg file that contains all 41 images as code or should I just do one image and animate the needle by creating an own pivot for it?
Note that the animation states would be hand in hand with a javascript code that "GET"s hex values via xmlHTTP which define the states of the device.
So i wanna turn the needle to 3 volts on the svg if I rotate the knob at the device.
I don't ask for a full solution but some hints if this would even be possible and what i need to read about.
Here is the img I am talking about as an example
Voltmeter
https://www.deviantart.com/blue-lovag/art/Voltmeter-759876423

An SVG with 41 groups in it might be a big file. If you create an SVG containing just one image, where the needle is a <g> group with an ID defined on it, you can refer to that group from JavaScript and have the needle rotate -- even with a smooth animation.
You might define a CSS class for each state the needle can be in, with the rotation in it:
.pos20 {
transform: rotate(45deg);
}
There are some gotchas with Internet Explorer support for this, so you may have to set an attribute on the group directly:
<g transform="rotate(45deg)">...</g>
Please refer to this article on CSS-Tricks for details on SVG transformations.

Related

How to crop images in React Native, so that it'll be like a circular shape instead of rectangle one?

I do have some pictures, and I need to crop them in a circular shapes before using them in React Native to use as ViroImage in react-viro (a library that render 360Images).
I can not apply much styles to the pictures and the borderRadius doesn't seem to solve my problem.
create a container with border radius = 30 and then place your image inside it
I've created react-native-image-tools-wm library when I had to process an image on the client and couldn't find anything worth using. Try it.
Example:
const image = Image.resolveAssetSource(require('./my-image.jpg)).uri;
const maskImage = Image.resolveAssetSource(require('./mask-image.png)).uri;
RNImageTools.mask(image, maskImage).then(({ uri, width, height }) => {
// Sync with your app state
});
Please note that your mask image should be black on white on iOS and black on transparent on Android. Black part will be replaced with your image and white/transparent will become transparent. You can use .android and .ios suffix on names and RN will load them conditionally.
You can also create a mask using createMaskFromShape method but you'll have to generate shape points yourself.

Image on HTML5 canvas only appearing for one frame

Long time lurker but never made an account. Just wanted to preface that I'm by no means a dev and just tinkering and experimenting for fun, so I apologise in advance if I seem really dumb.
I'm working on a dynamic overlay for Twitch streaming and was previously using AS3 but I've switched over to HTML5 now. I'm trying to load an image onto the canvas (which will eventually be a profile picture fetched using Twitch API... but one step at a time). I'm using Adobe Animate and I have the following so far applied in Actions on the first frame of the layer:
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
show_image();
function show_image() {
source_image = new Image();
source_image.src = 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png';
source_image.onload = function () {
context.drawImage(source_image, 100, 100);
}
}
When I hit Ctrl+Enter and see it in Chrome, the image appears for the first frame then disappears. I'm not sure how I'm supposed to get it to stay indefinitely. I need to be able to animate it later, and it'll change depending on the latest follow/donation/sub, etc.
I tried extending the frame itself in the timeline, however, this just changed long how it took to loop and didn't make the image itself stay longer. I'm probably missing something really simple!
Any help would be appreciated. Thanks!
Your code is okay if your approach is using a canvas with HTML and JS, without any libraries involved. However, this is not the case, as you are using Animate, and the way to draw graphics with it is different than using default canvas methods like drawImage().
Animate includes the CreateJS suite, which includes the EaselJS library ,and this allows you to use another tools to draw to your canvas. Two or them are the Stage object, the visual container of your animate project, and the Bitmap object, who represents an image, canvas or video. For effects of this question, only both objects are required.
Note that the code below is only for the first frame:
/* It is not necessary to declare the canvas or stage element,
as both are already declared. At this point the stage is ready to be drawn */
show_image();
function show_image() {
var source_image = new Image();
source_image.src = 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png';
source_image.onload = function(event) {
/* A new Bitmap object is created using your image element */
var bmp = new createjs.Bitmap(event.currentTarget);
/* The Bitmap is added to the stage */
stage.addChild(bmp);
}
}

animating a path on click - css timeframes or js/jquery?

I want to create an animation of a path, like a journey/timeline. The user is shown a circle (eventually to be an image), when they click this circle the animation begins and shows a path animating/traveling to another circle with a fade in effect. I have attached an image which I think explains my idea best.
My question is - what would be the recommended way of doing this? css animation or is there a jquery library that would be helpful?
Thank you
I would take svg as base. With Inkscape (or similar) like that, you can design the path visually and include the blue circle.
Than you can inject the svg-code in your html like so (copy the svg code from the generated file):
<div class="svg-container">
<svg>…</svg>
</div>
Finally you can use javascript to reference the circle and the path:
var path = document.querySelector('.path'), //these selectors are just arbitrary
circle = document.querySelector('.circle');
To get a point on the path, you can use:
var point = path.getPointAtLength();
For animation, I assume that you basically know how to do that, since this would be too much to explain here. But lets say that p is the progress of you animation and will be in the range [0,1]. To calculate a point at a given p could be done like so:
let pointAtT = (path, t) => {
let l_total = path.getTotalLength();
return path.getPointAtLength(l_total * t);
}
Having that, you can use the x and y coordinate to manipulate the circle. Be aware of possibly applied transformations, that is why I recommend to transform everything to global coordinate space, calculate there and transform the result back to the item's coordinate space.
Documentation on mdn
There are a some svg libraries that might help you: svg.js, snap.svg and Raphaël.

animating svg pan when manually setting pan.x and pan.y

I have a dynamically generated svg image that I am using Ariutta's svg-pan-zoom plugin with. When I double click an svg image, I set pan.x = centerOfScreenX, and pan.y = centerOfScreenY to center the image in the middle of the screen. ie:
$('.svg').dblclick(function(){
zoom.pan({'x':centerOfScreenX, 'y':centerOfScreenY });
});
Currently this causes the image to just suddenly move to the center of the screen. Is there a way I can animate this change in pan position so that the image doubleclicked moves along a path to the center of the screen instead?
Bumbu suggested two solution paths (see answers below), and I have taken a stab at the first. My attempt did not work however, and I do not know why.
// centerOfScreenX and centerOfScreenY are the correct values that pan.x and
// pan.y should have to center the svg in the middle of the screen
// xInterval and yInterval break the distance between the current pan
// position and the desired pan position into 10 steps
var xInterval = (centerOfScreenX - pan.x)/10;
var yInterval = (centerOfScreenY - pan.y)/10;
while( pan.x !== centerOfScreenX && pan.y !== centerOfScreenY ){
if(pan.x !== centerOfScreenX){
pan({'x': pan.x + xInterval })
}
if(pan.y !== centerofScreenY){
pan({'y': pan.y + yInterval })
}
}
When I try to run this code, the window freezes and I can no longer interact with my app, unless i close the window and reload it. My guess is that I am somehow triggering an infinite loop.
Currently there is no solution to do animation in an easy way.
There is a similar question (about animating zoom). The answer from there (adjusted to this one) is:
Currently such functionality is not supported. You could do it in 2 ways:
Use a twin library (or write you own function) and just call pan in small iterations multiple times. This may be slow but it is what many libraries do when implementing animation (eg. jQuery).
Use SVG animateTransform element. It seems to be the right way. But it needs some work to get it done.
You can actually try to implement second solution by listening to zoom
events, canceling them and adding animateTransform manually to the SVG.
When your animation is done, call zoom again but this time don't
cancel it (necessary to update library inner state).
There is an ongoing discussion about next version of library that would be more extensible. This would allow to write plugins. Animation is one of the candidates. But it will take some time (few months) to do this.
If you'll be able to find a temporary solution - share it here or on github and we'll be happy to update the library or integrate it in next version.
Edit
I added a simple example how this kind of animation can be implemented.
You can find it in demo/simple-animation.html
I used a simple interval there. A more advanced version should take into account how much time passed since last interval call and send the right amount for pan. But even like this it works very well.
The library internally uses requestAnimationFrame so you can call panBy even every millisecond and it shouldn't block the browser.

A roulette wheel in javascript

I am trying to build a roulette wheel in javascript.
I found this example: http://www.switchonthecode.com/tutorials/creating-a-roulette-wheel-using-html5-canvas but I find the look & feel not very terrible.
Since my roulette will have a limited number of option, I was thinking of using an image and then place text above with the proper angle. When spinning the wheel, I would just make the image and the text turn.
Is it a good approach? Are there some better approaches?
You can also do that with css3 rotation but it will work only on newer browsers
You can do even better. Make hole roulette wheel in SVG, it support animation and it can be programmed in javascript
Well I think the best approach in terms of creating something quickly and easily is to use an existing Javascript library for creating spinning prize/winning wheels.
I am the creator of a Javascript library called Winwheel.js which is specifically for this purpose. See http://www.dougtesting.net
One great feature about my Winwheel.js is that you can mix a graphically rich image for the face of the wheel with code-drawn text for the segment labels, so if you want the wheel to look really nice but have the flexibility of configurable text, you can.
Here is an example of the code needed to do this using Winwheel.js...
var myWheel = new Winwheel({
'drawMode' : 'image',
'drawText' : true, // Set this to true for text to be rendered on image.
'numSegments' : 4,
'textOrientation' : 'curved', // Set text properties.
'textAlignment' : 'outer',
'textMargin' : 5,
'textFontFamily' : 'courier',
'segments' : // Set segment text
[
{'text' : 'Television'},
{'text' : 'Mobile Phone'},
{'text' : 'Old Radio'},
{'text' : 'Computer'}
]
});
var wheelImg = new Image();
wheelImg.onload = function()
{
myWheel.wheelImage = wheelImg;
myWheel.draw();
}
wheelImg.src = "wheel_image.png";
There is a full set of tutorials on my site explaining how to use Winwheel.js, but the particular one about Image wheels can be found here http://dougtesting.net/winwheel/docs/tut9_creating_with_an_image
Thanks,
DouG
jQuery is not necessary. The example was done using the HTML5 Canvas element, which is probably the only (clean) way you could do it without Flash or Silverlight. You can customize the colors using the first array in the code, or any other nuance of it with a little tinkering.
You could use an SVG (Scalable vector graphics format) image and rotate it.
I wrote http://roulette.dabase.com/ as an exercise which works on mobile browsers I've tried.
I actually implemented a similar mini-game on my site not too long ago. No canvas, no SVG, no jQuery.
I used a simple image for the board (more specifically as a background-image), then placed a <div> on it to be the ball.
<div id="board"><div></div></div>
CSS:
#board {
width:256px;
height:256px;
background-image:url('gameboard.png');
position:relative;
transform-origin:50% 50%;
}
#board>div {
position:absolute;
margin-left:-7px;
margin-top:-7px;
border:7px outset #ccc;
width:1px; height:1px;
left:248px;
top:128px;
}
Then this JavaScript is used to position the ball when spinning:
function placeBall(angle) {
var board = document.getElementById("board"), ball = board.children[0];
ball.style.left = (128+Math.cos(angle)*120)+"px";
ball.style.top = (128-Math.sin(angle)*120)+"px";
board.style.transform = "rotate(-"+angle+"rad)";
}
This will result in the ball spinning around the wheel in older browsers. In newer browsers, the ball will stay in place (but the border shading will spin) while the entire board rotates. You can of course use a combination of the two if you do something different on the transformation (for example, "rotate(-"+(angle/2)+"rad)")

Categories