It is my first day using javascript.
I am trying to start with a simple task is to add a sin-wave to the plot then remove it. (The remove function does NOT work but, the add function does work)
I am also trying to use a slide bar to change the frequency of the wave
'''
<script crossorigin src="https://unpkg.com/react#18/umd/react.production.min.js">
</script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-
dom.production.min.js"></script>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="tester" style="width:600px;height:250px;"></div>
<div><button onclick="create_sin()">add</button></div>
<div><button onclick="remove()">remove</button></div>
<div class="slidecontainer">
<input type="range" min="1" max="100" value="50" class="slider" id="myRange">
</div>
</body>
<script>
var x1 = []
var y1 = []
//fill the arrays of the sin wave
function create_sin() {
if (x1.length != 0) { return }
var screen_size = 40
var period = 4
var freq = 1 / period
var omega = 2 * Math.PI * freq
var step_size = 4 / screen_size
var counter = 0
while (counter <= 40) {
x1.push(counter)
y1.push(Math.sin(omega * counter))
counter = counter + step_size
}
Plotly.redraw(TESTER)
}
function remove() {
x1 = []
y1 = []
Plotly.redraw(TESTER)
}
TESTER = document.getElementById('tester')
Plotly.newPlot(TESTER, [{
x: x1,
y: y1,
line: { shape: 'spline' },
}], {
margin: { t: 0 }
})
</script>
</html>
'''
Related
I'm using paper js to draw an animated set of rectangles. Since there will be several HTML pages in this project, I tried adding the menu HTML programmatically using javascript. However, once the menu script loads, paper js stops redrawing.
I used a timer to delay the loading of the menu script to ascertain if it was any other issue. The animation definitely plays normally right before the menu script loads.
Any other element added programmatically works fine. It's the only paper that stops redrawing.
HTML
<head>
<script src="./scripts/paper-full.js"></script>
<script type="text/javascript" src="./scripts/menu.js"></script>
<script
type="text/paperscript"
src="./scripts/paper.js"
canvas="myCanvas"
></script>
<!-- <link rel="stylesheet" href="./styles/style.css" /> -->
<link
href="https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap"
rel="stylesheet"
/>
</head>
<body id="body">
<div id="main">
<label id="stats"></label>
<canvas id="myCanvas" resize></canvas>
</div>
</body>
MENU
var label = '<label id="stats"></label>';
var divO = '<div id="menu" class="menu">';
var divC = "</div>";
var html =
'Home ProjectsBlog About';
setTimeout(() => {
document.body.innerHTML += label + divO + html + divC;
}, 500);
PAPER
var length = 35;
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++)
path.add(start + new Point(i * length, 0));
function onMouseMove(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
var vector = segment.point - nextSegment.point;
vector.length = length;
nextSegment.point = segment.point - vector;
}
path.smooth({ type: 'continuous' });
}
function onMouseDown(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
function onMouseUp(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
Your problem comes from the fact that you are resetting the document.body.innerHTML and this somehow breaks Paper.js coupling with the canvas.
What I would suggest is using a dedicated element to insert your dynamic content into the DOM, rather that injecting it into the <body> directly.
Here is an updated code demonstrating the solution. Have a close look at the lines:
<div id="menu-container"></div>
document.querySelector('#menu-container').innerHTML = label + divO + html + divC;
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/paper"></script>
<link
href="https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap"
rel="stylesheet"
/>
</head>
<body id="body">
<div id="main">
<label id="stats"></label>
<canvas id="myCanvas" resize></canvas>
</div>
<div id="menu-container"></div>
<script type="text/javascript">
var label = '<label id="stats"></label>';
var divO = '<div id="menu" class="menu">';
var divC = "</div>";
var html =
'Home ProjectsBlog About';
document.querySelector('#menu-container').innerHTML = label + divO + html + divC;
</script>
<script type="text/paperscript" canvas="myCanvas">
var length = 35;
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var points = 20
var start = view.center / [10, 1];
for (var i = 0; i < points; i++)
path.add(start + new Point(i * length, 0));
function onMouseMove(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
var vector = segment.point - nextSegment.point;
vector.length = length;
nextSegment.point = segment.point - vector;
}
path.smooth({ type: 'continuous' });
}
function onMouseDown(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
function onMouseUp(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
</script>
</body>
</html>
I have some chart what have two colors (Red and Blue).
Example
.
I use Chartjs
How it most work:
I have values, for example:
red from 1 to 350,
blue from 351 to 1000
Warning: Values (red and blue) can changes.
Ok, we have values, now I wont rotate my chart X counts and stop on value 256, (this is red color).
(start on top - Place of Start)
Q: How I can do this?
For example, I find some code what random spin (rotate) my chart:
var spin = function () {
var timeOut = function () {
// called by setTimeout to update the chart after rotation been changed
dynChart.update();
}
// generate random angle
var newAngle = Math.random() * 1080 + currAngle;
for (var angle = currAngle, interval = 100; angle < newAngle; angle += 1, interval += 5) {
dynChart.options.rotation = angle;
setTimeout(timeOut, interval);
}
//currAngle = dynChart.options.rotation;
}
This could help you:
var config = {
type: 'pie',
data: {
datasets: [{
data: [
300,
700
],
backgroundColor: [
window.chartColors.red,
window.chartColors.blue,
],
label: 'Dataset 1'
}]
},
options: {
responsive: true,
rotation: 0,
animation: {
duration: 2000
}
}
};
var myPie;
window.onload = function() {
create();
};
function create() {
var ctx = document.getElementById('chart-area').getContext('2d');
config.data.datasets[0].data = [$("#redValue").val(), $("#blueValue").val()]
config.options.rotation = -Math.PI / 2;
config.options.animation.duration = 2000;
myPie = new Chart(ctx, config);
// console.log(myPie);
}
function rotate() {
var fromDegree = 0;
var toDegree = 360 * (parseFloat($("#stopValue").val())) /
(parseFloat($("#redValue").val()) + parseFloat($("#blueValue").val()));
rotatePie(0, 360, 8,
function() {
rotatePie(0, 360, 15,
function() {
rotatePie(fromDegree, toDegree, 30,
function() {})
})
});
}
function rotatePie(fromDegree, toDegree, delay, callback) {
var rotation = -Math.PI / 2 - fromDegree * 2 * Math.PI / 360;
var stopRotation = -Math.PI / 2 - toDegree * 2 * Math.PI / 360;
var intervalId = setInterval(frame, delay);
function frame() {
if (rotation <= stopRotation) {
console.log('2');
clearInterval(intervalId);
callback();
} else {
rotation = rotation - Math.PI * 0.03;
myPie.config.options.rotation = rotation;
myPie.config.options.animation.duration = 0;
myPie.update();
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.chartjs.org/samples/latest/utils.js"></script>
<script src="https://www.chartjs.org/dist/2.7.3/Chart.bundle.js"></script>
<div id="canvas-holder" style="width:40%; margin: 20px">
<canvas id="chart-area"></canvas>
</div>
Red Value: <input id="redValue" type="number" value="300" />
<br/> Blue Value: <input id="blueValue" type="number" value="700" />
<br/>
<button type="button" onclick="create()">Create</button>
<br/> <br/> Stop On: <input id="stopValue" type="number" value="350" />
<br/><br/>
<button type="button" onclick="rotate()">Rotate</button>
I am trying to make a vector calculator to practice my jquery skills and I have an Issue. I have a .option div where I have fields for the force and the angle. If I click the #calc_v button another field is inserted.
<div class="option">
<h2>Vectors</h2>
<a class="close">Close X</a><br/>
<div id="move">1.<input type="number" step="0.01" id="N1"/> Newtons(or meters) à <input type="number" step="0.01" id="A1"/> Degrees
<br/></div>
<button id="calc_v">Calculer</button>
<a id="add_move">+ VECTOR</a>
<div id="log_v"></div>
here is my jquery code:
<script>
//vectors
var vector = 1;
$("#add_move").click(function () {
vector++;
$("#move").append(vector+".<input type='number' step='0.01' id='N"+vector+"'/> Newtons(ou mètres) à <input type='number' step='0.01' id='A"+vector+"'/> Degrées<br/>");
});
$("#calc_v").click(function(){
var x_v = 0;
var y_v = 0;
var ite = 0;
for(x=1; x <= vector; x++){
//for each added vector give it a var name
ite++;
var f = "#N"+ite;
var a = "#A"+ite;
//then, find its value
var force = $(f).val();
var f_val = parseFloat(force);
var angle = $(a).val();
var a_val = parseFloat(angle);
//analyse it
var cons_x = ((f_val)*(Math.cos(a_val))) * (180 / Math.PI);
var cons_y = ((f_val)*(Math.sin(a_val))) * (180 / Math.PI);
//add it to each x,y coords
x_v += cons_x;
y_v += cons_y;
}
$("#log_v").html("Coords: ("+ x_v + ","+ y_v + ") |f"+force +"|a"+ angle +"|i"+ ite+"|v"+vector);
});
I'm a beginner beginner. I can get the behavior that I want to occur, but instead of occurring in two separate SVGs, all the behavior is occurring in 'svg2' although I have selected the respective ids for 'svg1' and 'svg2' (or at least I think I did)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.2.0/raphael-min.js"></script>
<script src="logic.js"></script>
<title>Forms and Concentric Circles</title>
</head>
<body>
<h1>Forms and Concentric Circles</h1>
<div id="svg1"></div>
<div class="form">Add how many?
<input type="text" id="howmany" />
<button id="more">Add More</button></div>
<div id="svg2"></div>
<div class="form">
<button id="another">Add Another</button>
</div>
</body>
</html>
var paper;
disappear = function() {
this.remove();
}
spin = function(r) {
angle = Math.random()*1440 - 720;
initial = { 'transform': 'r0' }
final = { 'transform': 'r' + angle}
r.attr(initial);
r.animate(final, 2000);
}
addMore = function() {
rectNum = $('#howmany').val();
for (step = 0; step < rectNum; step += 1) {
x = Math.random() * 180;
y = Math.random() * 180;
r = paper.rect(x, y, 20, 20);
filled = {
'fill': '#ddf'
}
r.attr(filled);
r.click(disappear);
spin(r);
}
}
radius = 10
morecircles = function() {
paper.circle(100, 100, radius);
radius = radius + 10;
}
setup = function() {
paper = Raphael('svg1', 200, 200);
$('#more').click(addMore);
paper = Raphael('svg2', 200, 200);
$('#another').click(morecircles);
}
$(document).ready(setup);
change the name for the second svg for example
paper2.circle
and in your setup function it should be
paper2.Raphael('svg2',200,200)
So I have 2 problems. first is the clearInterval does not seem to be working as the image continues to rotate when the mouse cursor is over the image. second is the rightDisc is the setInterval seems to not work on the rightDisc. all the other functions do work. I tried looking into threading with web workers but that's all sorts of confusing me.
<html>
<head>
<script src="../js/jquery-1.6.4.min.js"></script>
<script src="../js/imgRotate.js"></script>
<script>
$(function()
{
$("#leftDisc").rotate();
$("#rightDisc").rotate();
});
</script>
</head>
<body>
<div>
<img id="turnTableImage" src="turntable.jpg" height="400" width="600" alt="" />
</div>
<div id="leftDisc" style="margin-top: -280px; margin-left: 50px">
left<img id="leftDiscImg" class="discs" height="200" src="disc.png" alt="" />
</div>
<div id="rightDisc" style="margin-top: -300px; margin-left: 350px">
<img id="rightDiscImg" class="discs" src="disc.png" alt="" />right
</div>
</body>
imgRotate.js
(function($) {
$.fn.rotate = function() {
var img = this.find(".discs");
var imgpos = img.position();
var x, y, xCenter, yCenter, x1, y1, deg = 1, drag = false;
var interval = setInterval(function() {
deg++;
$("#leftDiscImg").css("transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("-moz-transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("-webkit-transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("-o-transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("ms-transform","rotate("+deg+"deg)");
}, 20);
$(window).load(function() {
img.removeAttr("width");
img.removeAttr("height");
xCenter = imgpos.left + (img.width() / 2);
yCenter = imgpos.top + (img.height() / 2);
});
img.mousemove(function(e) {
x1 = e.pageX;
y1 = e.pageY;
x = x1 - xCenter;
y = y1 - yCenter;
r = 360 - ((180/Math.PI) * Math.atan2(y,x));
if (drag == true) {
img.css("transform","rotate(-"+r+"deg)");
img.css("-moz-transform","rotate(-"+r+"deg)");
img.css("-webkit-transform","rotate(-"+r+"deg)");
img.css("-o-transform","rotate(-"+r+"deg)");
img.css("ms-transform","rotate(-"+r+"deg)");
}
});
img.mouseover(function() {
clearInterval(interval);
deg = 1;
if (drag == false) {
drag = true;
} else {
drag = false;
}
});
img.mouseout(function() {
drag = false;
interval = setInterval(function() {
deg++;
$("#leftDiscImg").css("transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("-moz-transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("-webkit-transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("-o-transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("ms-transform","rotate("+deg+"deg)");
}, 20);
});
};
})( jQuery );