JSFiddle - React, Tailwind, and code Playground
by _kdts
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/5.10.3/math.min.js"></script>
<!--
https://cdnjs.cloudflare.com/ajax/libs/mathjs/5.10.3/math.min.js
-->
<canvas id="drawboard" width="450" height="450"></canvas>
<div id="logArea"></div>
CSS
#drawboard {
border: 1px solid #ccc;
}
JavaScript
/*
using math.* from mathjs
*/
const logAreaElement = document.getElementById('logArea');
const canvasElement = document.getElementById('drawboard');
const canvas = canvasElement.getContext('2d');
const inputElement = document.createElement('input')
logAreaElement.appendChild(inputElement)
let expression = 'x*sin(x+t)',
scope = { x: 0, t: 0 },
time = 0,
dt = 0.05;
//tree = math.parse(expression, scope);
function evaluateMathExpression(_dx){
scope.x = _dx;
scope.t = time
//return tree.eval(scope)
return math.eval(expression, scope)
}
function drawCurve(){
let scaleX = 0,
scaleY = 0,
x, y,
xPixel, yPixel;
// coordinate axices
const xMin = -5,
xMax = 5,
yMin = -10,
yMax = 10,
nPoints = 6*(xMax-xMin);
//canvas.save();
//canvas.translate(15, 0);
canvas.clearRect(0, 0, canvasElement.width, canvasElement.height)
canvas.beginPath()
for(let i = 0; i < nPoints; i++){
scaleX = i/(nPoints - 1)
x = scaleX * (xMax - xMin) + xMin
y = evaluateMathExpression(x)
scaleY = (y - yMin) / (yMax - yMin)
// flip to match math coordinate with (0,0) at the bottom left
scaleY = 1 - scaleY;
xPixel = scaleX * canvasElement.width
yPixel = scaleY * canvasElement.height
canvas.lineTo(xPixel, yPixel)
}
canvas.moveTo(0, canvasElement.height/2)
canvas.lineTo(canvasElement.width, canvasElement.height/2)
canvas.moveTo(canvasElement.width/2, 0)
canvas.lineTo(canvasElement.width/2, canvasElement.height)
canvas.stroke()
}
initTextField()
drawCurve()
animate()
let keyupPauseTimeout;
function initTextField(){
//expressionFromHash = getHashValue()
expression = getHashValue() || inputElement.value || expression;
inputElement.value = expression;
inputElement.addEventListener('keyup', function(e){
clearTimeout(keyupPauseTimeout)
expression =...