I have some code in a graph and I already tried this code in canvas but for loop condition based in this code x&y value ellipse shape draw the canvas.
I want to how to add the for loop inside the canvas and plot the ellipse shape.
#mycanvas{
position:absolute;
width:250px;
height:400px;
top:200px;
left:200px;
}
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet"type="text/css" href="newellipse.css">
<script src="jfile/myquery.js"></script>
</head>
<body>
<input id="ipvalue" type="text" value="25x^2+4y^2+100x-40y=-100">
<button onclick="checkFruit()">solve</button>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
<canvas id="myCanvas"width="578" height="400" style="position:absolute;left:220px;top:50px";>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var step = 2*Math.PI/20; // see note 1
var h = 150;
var k = 150;
var r = 80;
ctx.beginPath(); //tell canvas to start a set of lines
for(var theta=0; theta < 2*Math.PI; theta+=step) {
var x = h + r*Math.cos(theta) ;
var y = k - 0.5 * r*Math.sin(theta) ; //note 2.
ctx.lineTo(x,y);
}
ctx.closePath(); //close the end to the start point
ctx.stroke(); //actually draw the accumulated lines
function checkFruit() {
var reg =/([\-+])?\s*(\d+)?([a-zA-Z])\b/g;
var equation = id("ipvalue").val();
var spli = reg.exec(equation);
alert(spli);
var y = document.getElementById("ipvalue").value;
switch(y) {
case "25x^2+4y^2+100x-40y=-100":
text = "Formula for Ellipse x^2/a^2+y^2/b^2=1";
text1= "First RHS side value consider for 1";
text2= "LHS side divide by RHS value for 16";
text3= "Take a square root of denaminater value";
text4= "Find the x and y value";
document.getElementById("demo").innerHTML = text;
document.getElementById("demo1").innerHTML = text1;
document.getElementById("demo2").innerHTML = text2;
document.getElementById("demo3").innerHTML = text3;
document.getElementById("demo4").innerHTML = text4;
break;
// add the default keyword here
}
}
</script>
</body>
<html>
<!DOCTYPE HTML>
<html>
<head>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled: true,
title:{
text: "Try Zooming And Panning"
},
axisY:{
includeZero: false
},
title: {
text: "Graph"
},
data: [{
type: "spline",
dataPoints: [
{ x:-15, y:0 },
{ x:-10, y:18 },
{ x:0, y:20 },
{ x:10, y:18 },
{ x:15, y:0 },
{ x:10, y:-18 },
{ x:0, y:-20 },
{ x:-10, y:-15 },
{ x:-15, y:0 },
]},
]
});
chart.render();
}
</script>
</head>
<body>
<div id="correct"style="position:absolute;width:500px;height:70%;top:80px;left:250px;">
<div id="chartContainer" style="height: 400px; width: 100%;">
</div>
</div>
</body>
</html>
In that modal how to x and y value inside the for loop condition base draw the ellipse graph?
<canvas> must be closed as shown here.
The style attribute on <canvas> must have semicolon (;) before double-quote (").
html
<canvas id="myCanvas"width="578" height="400" style="position:absolute;left:220px;top:50px;"></canvas>
I personally prefer document.querySelector(...) over document.getElementById(...).
I took liberty to increase the number of lines for ellipsis from 20 to 1000.
My console says ReferenceError: id is not defined. So instead use document.querySelector('#ipvalue').
Also note that .val(...) works but with jQuery. And html uses .value property. So, the code become document.querySelector('#ipvalue').value.
I touched deliberately at your code structure... (I mean the checkFruit(...) function)
<!DOCTYPE HTML>
<html>
<head>
<!--<link rel="stylesheet"type="text/css" href="newellipse.css">
<script src="jfile/myquery.js"></script>-->
<meta charset="UTF-8">
</head>
<body>
<input id="ipvalue" type="text" value="25x^2+4y^2+100x-40y=-100">
<button onclick="checkFruit()">solve</button>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
<canvas id="myCanvas"width="578" height="400" style="position:absolute;left:220px;top:50px;"></canvas>
<script>
var canvas = document.querySelector("#myCanvas");
var context2d = canvas.getContext("2d");
var step = 2*Math.PI/1000; // see note 1
var h = 150;
var k = 150;
var r = 80;
context2d.beginPath(); //tell canvas to start a set of lines
for(var theta = 0; theta < 2*Math.PI; theta += step)
{
var x = h + r*Math.cos(theta);
var y = k - 0.5 * r*Math.sin(theta); //note 2.
context2d.lineTo(x,y);
}
context2d.closePath(); //close the end to the start point
context2d.stroke(); //actually draw the accumulated lines
var splitter = /([\-+])?\s*(\d+)?([a-zA-Z])\b/g;
var source = document.querySelector('#ipvalue');
var target = document.querySelector("#demo");
var target1 = document.querySelector("#demo1");
var target2 = document.querySelector("#demo2");
var target3 = document.querySelector("#demo3");
var target4 = document.querySelector("#demo4");
function checkFruit()
{
var equation = splitter.exec(source.value);
console.log('SOURCE: ', source.value);
console.log('EQUATION: ', equation);
console.log('SUGGESTION: ', source.value.match(splitter));
var y = source.value;
switch(y)
{
case "25x^2+4y^2+100x-40y=-100":
var text = "Formula for Ellipse x^2/a^2+y^2/b^2=1";
var text1 = "First RHS side value consider for 1";
var text2 = "LHS side divide by RHS value for 16";
var text3 = "Take a square root of denaminater value";
var text4 = "Find the x and y value";
target.innerHTML = text;
target1.innerHTML = text1;
target2.innerHTML = text2;
target3.innerHTML = text3;
target4.innerHTML = text4;
break;
}
}
</script>
</body>
<html>
Related
Im trying to scale an image using variables rather than a set in stone scale. I know using "scale(0.5,0.5)" works but I want to do something like "scale(x,y)" so the scale factor changes depending on what variables x and y are, However when I try doing this, the image will no longer scale like it did when it had a set scale factor. How can I solve this? Thanks for any help. Here's an example of what I mean.
<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="img_pulpit.jpg">
<button onclick="myFunction()">Try it</button>
<script>
var a = document.getElementById("myImg");
var d = 5
var e = 10
var f = d/e
var g = 10
var h = 30
var i = g/h
function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale(f, i)";
}
</script>
</body>
</html>
Just use string concatenation ("scale(" + f + ", " + i + ")") or string interpolation (`scale(${f}, ${i})`).
function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale(" + f + "," + i + ")";
}
You need to use concat the value of f and i
document.getElementById("myImg").style.WebkitTransform = "scale("+f+","+i+")";
<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="https://lh3.googleusercontent.com/gN6iBKP1b2GTXZZoCxhyXiYIAh8QJ_8xzlhEK6csyDadA4GdkEdIEy9Bc8s5jozt1g=w300">
<button onclick="myFunction()">Try it</button>
<script>
var a = document.getElementById("myImg");
var d = 5
var e = 10
var f = d/e
var g = 10
var h = 30
var i = g/h
function myFunction() {
document.getElementById("myImg").style.WebkitTransform = "scale("+f+","+i+")";
}
</script>
</body>
</html>
new to js and html. have tried different answers here and many websites but for some reaon my code is still not working. i have created a plugin called mazePlugin.js, another script called test.js and my html file called test.html.
once a button is clicked the test script is invoked, sends an ajax request to my server(checked it works) and upon success it attempts to call my plugin and draw a maze. i know there might be problems with where i define the canvas. but that is not my current issue.
my html
<!DOCTYPE html> <html> <head>
<meta charset="utf-8" />
<title>test page</title> </head> <body>
<p id="paragraph">first paragraph</p>
<p id="paragraph2">2nd paragraph</p>
<input id="button" type="button" value="start game"/>
<form>
Name:<br/>
<input id="name" type="text"/><br/>
Columns:<br/>
<input id="col" type="number"/><br/>
Rows:<br/>
<input id="row" type="number"/> </form>
<script type="text/javascript" src="../Scripts/jquery-3.2.1.js"></script>
<script type="text/javascript" src="../Scripts/mazePlugin.js"></script>
<script type="text/javascript" src="../Scripts/test.js"></script>
</body>
</html>
my plugin
(function($) {
$.fn.maze = function (data) {
var mazeObject = {
draw: function() {
var rows = data["Rows"];
var cols = data["Cols"];
var cellWidth = 300 / cols;
var cellHeight = 300 / rows;
var initialRow = data["Start"]["Row"];
var initialCol = data["Start"]["Col"];
var mazeAsString = data["Maze"];
//draws the maze
var current = 0;
for (var i = 0; i < rows; i++) {
for (var j = 0; j < cols; j++) {
if (mazeAsString[current] == '1') {
context.fillRect(cellWidth * j, cellHeight * i, cellWidth, cellHeight);
}
current++;
}
}
//creating players image
var united = new Image();
united.src = "../Style/united.png";
united.onload = function() {
context.drawImage(united, initialRow, initialCol, cellWidth, cellHeight);
}
return this;
}
};
return mazeObject;
};
}(jQuery));
my test.js
$('#button').click(function () {
var canvas = document.createElement('canvas');
canvas.id = "mazeCanvas";
canvas.width = 300;
canvas.height = 300;
canvas.style = "border:2px black solid";
document.body.appendChild(canvas);
var name = $('#name').val();
var rows = $('#row').val();
var cols = $('#col').val();
var context = canvas.getContext("2d");
var mazeObject;
$.ajax({
url: "Http://localhost:52800/api/Maze",
data: { 'name':name, 'rows':rows, 'cols':cols },
success: function (data) {
mazeObject = $.fn.maze(data);
mazeObject.draw();
},
error: function() {
alert('an error has occurred');
}
});
});
the response i get is
test.js:40 Uncaught TypeError: $.fn.maze is not a function
at Object.success (test.js:40)
at fire (jquery-3.2.1.js:3317)
at Object.fireWith [as resolveWith] (jquery-3.2.1.js:3447)
at done (jquery-3.2.1.js:9272)
at XMLHttpRequest. (jquery-3.2.1.js:9514)
You are incorrectly calling your plugin. It should be:
mazeObject = $.maze(data);
I'm making a small game for university and I need to add different shapes in my project. I'm talking about Triangle, Rectangle, Pentagon, Hexagon, Heptagon, Octagon....n-gon. I need all the shapes to be convex regular polygons and being able to color the inside. I'm thinking of drawing SVG shapes, but I'm not sure what the formula should be given only the n-sides of the shape to be generated. If there is a JS plugin that I can just include with Bower and generate the shapes, that will be great. There is also the problem of coloring them and after that being able to change the color with animation, but step by step.
Below is a method I use to build polygons. It provides a random fill color. See if this helps.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Create SVG Polygons</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body style='padding:10px;font-family:arial'>
<center>
<h4>Create SVG Polygons</h4>
<div style='width:90%;background-color:gainsboro;text-align:justify;padding:10px;border-radius:6px;'>
Create inline svg with random circles, ellipses, polygons, and rectangles used for test environment.
</div><br />
<div id="svgDiv" style='border:1px black outset'>
<svg id="mySVG" />
</div><br />
Number Of Elements:<input type=text id=elemsValue size=1 value=1200 />
SVG Width:<input type=text id=widthValue size=1 value=600 />
SVG Height:<input type=text id=heightValue size=1 value=400 />
Element Sze:<input type=text id=sizeValue size=1 value=20 />
<button onClick=go()>go</button><br />
<script>
//---button---
function go()
{
var elems=parseInt(elemsValue.value)
var svgWidth=parseFloat(widthValue.value)
var svgHeight=parseFloat(heightValue.value)
var elemSize=parseFloat(sizeValue.value)
//---clear prevoius---
mySVG.removeChild(document.getElementById("globG"))
svgGLOB(elems,svgWidth,svgHeight,elemSize)
}
function svgGLOB(elems,svgWidth,svgHeight,elemSize)
{
/* ---fill empty inline SVG element---
<div id="svgDiv"><svg id="mySVG" /></div>
*/
var NS="http://www.w3.org/2000/svg"
mySVG.setAttribute("width",svgWidth)
mySVG.setAttribute("height",svgHeight)
svgDiv.style.width=svgWidth+"px"
svgDiv.style.height=svgHeight+"px"
var globG=document.createElementNS(NS,"g")
globG.id="globG"
globG.setAttribute("stroke","black")
globG.setAttribute("stroke-width",1)
mySVG.appendChild(globG)
var points=randomPoints(elems,svgWidth,svgHeight,elemSize)
var n=points.length
var circleCnt=0
var ellipseCnt=0
var rectCnt=0
var polygonCnt=0
var RandomElems=[]
RandomElems[0]="circle"
RandomElems[1]="rect"
RandomElems[2]="ellipse"
RandomElems[3]="polygon_3"
RandomElems[4]="polygon_4"
RandomElems[5]="polygon_5"
RandomElems[6]="polygon_6"
RandomElems[7]="polygon_7"
RandomElems[8]="polygon_8"
RandomElems[9]="polygon_9"
RandomElems[10]="polygon_10"
RandomElems[11]="polygon_11"
RandomElems[12]="polygon_12"
for(var k=0;k<n;k++)
{
var rand=rdm(0,12)
var elemStr=RandomElems[rand]
if(!elemStr.indexOf("_"))
var elemSt=elemStr
else
var elemSt=elemStr.split("_")[0]
var elem=document.createElementNS(NS,elemSt)
if(elemSt=="circle")
{
elem.setAttribute("r",elemSize)
elem.setAttribute("fill",rcolor())
elem.setAttribute("cx",points[k][0])
elem.setAttribute("cy",points[k][1])
elem.id=elemSt+(circleCnt++)
}
else if(elemSt=="ellipse")
{
elem.setAttribute("rx",elemSize)
elem.setAttribute("ry",elemSize/2)
elem.setAttribute("fill",rcolor())
elem.setAttribute("cx",points[k][0])
elem.setAttribute("cy",points[k][1])
elem.id=elemSt+(ellipseCnt++)
}
else if(elemSt=="rect")
{
elem.setAttribute("width",elemSize)
elem.setAttribute("height",elemSize)
elem.setAttribute("fill",rcolor())
elem.setAttribute("x",points[k][0])
elem.setAttribute("y",points[k][1])
elem.id=elemSt+(rectCnt++)
}
else if(elemSt=="polygon")
{
var pgonSides=parseInt(elemStr.split("_")[1])
var pgonPnts=polygon(pgonSides,elemSize,points[k][0],points[k][1])
elem.setAttribute("fill",rcolor())
elem.setAttribute("points",pgonPnts.join())
elem.id=elemSt+(polygonCnt++)
}
globG.appendChild(elem)
}
//---obtain a random whole number from a thru b---
function rdm(a,b)
{
return a + Math.floor(Math.random()*(b-a+1));
}
function randomPoints(elems,svgWidth,svgHeight,elemSize)
{
//--return format:[ [x,y],[x,y],,, ]
//---Generate random points---
function times(n, fn)
{
var a = [], i;
for (i = 0; i < n; i++) {
a.push(fn(i));
}
return a;
}
var width=svgWidth-2*elemSize
var height=svgHeight-2*elemSize
return RandomPnts = times(elems, function() { return [Math.floor(width * Math.random()) + elemSize, Math.floor(height * Math.random()) + elemSize] });
}
//---random color---
function rcolor()
{
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ )
{
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
function polygon(vCnt,radius,centerX,centerY)
{
var myPoints=[]
var polyXPts = Array(vCnt);
var polyYPts = Array(vCnt);
var vertexAngle = 360/vCnt;
//---init polygon points processor---
for(var v=0; v<vCnt; v++)
{
theAngle = (v*vertexAngle)*Math.PI/180;
polyXPts[v] = radius*Math.cos(theAngle);
polyYPts[v] = -radius*Math.sin(theAngle);
}
//--note points are CCW---
for(var v=0;v<vCnt; v++)
{
var point=[centerX+polyXPts[v],centerY+polyYPts[v]]
myPoints.push(point)
}
return myPoints
}
}
document.addEventListener("onload",init(),false)
function init()
{
svgGLOB(1200,600,400,20)
}
</script>
</body>
</html>
I'm trying to a find a way where I can click on individual pixels and then the XY coordinates of the pixel will be recorded/printed. I found the code below online, but it only shows the coordinates of the last-clicked pixel. Is there a way to save/print the coordinates of all the pixels that I have clicked. I'm doing this for a Java applet and this would make it much easier for me to make polygons.
I would prefer the output (when I click the pixels) to be like this, so that I can just copy & paste into java:
int [] x={x1,x2,x3,x4,x...};
int [] y={y1,y2,y3,y4,y...};
Here is the code I found:
<html>
<head>
<script language="JavaScript">
function point_it(event){
pos_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("pointer_div").offsetLeft;
pos_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("pointer_div").offsetTop;
document.getElementById("cross").style.left = (pos_x-1) ;
document.getElementById("cross").style.top = (pos_y-15) ;
document.getElementById("cross").style.visibility = "visible" ;
document.pointform.form_x.value = pos_x;
document.pointform.form_y.value = pos_y;
}
</script>
</head>
<body>
<form name="pointform" method="post">
<div id="pointer_div" onclick="point_it(event)" style = "background-image:url('image.jpg');width:2400px;height:1848px;">
<img src="point.gif" id="cross" style="position:relative;visibility:hidden;z-index:2;"></div>
You pointed on x = <input type="text" name="form_x" size="4" /> - y = <input type="text" name="form_y" size="4" />
</form>
</body>
</html>
<html>
<head>
<script language="JavaScript">
var x = [];
var y = [];
function point_it(event) {
pos_x = event.offsetX ? (event.offsetX) : event.pageX - document.getElementById("pointer_div").offsetLeft;
pos_y = event.offsetY ? (event.offsetY) : event.pageY - document.getElementById("pointer_div").offsetTop;
document.getElementById("cross").style.left = (pos_x - 1);
document.getElementById("cross").style.top = (pos_y - 15);
document.getElementById("cross").style.visibility = "visible";
x.push(pos_x);
y.push(pos_y);
document.getElementById("form_x").innerHTML = x;
document.getElementById("form_y").innerHTML = y;
};
function remove_it() {
x.pop();
y.pop();
document.getElementById("form_x").innerHTML = x;
document.getElementById("form_y").innerHTML = y;
}
</script>
</head>
<body>
<form name="pointform" method="post">
<div id="pointer_div" onclick="point_it(event)" style="background-image:url('image.jpg');width:2400px;height:1848px;">
<img src="point.gif" id="cross" style="position:relative;visibility:hidden;z-index:2;">
</div>
You pointed on
<br>x = <span id="form_x"></span>
<br>y = <span id="form_y"></span>
<br>
<button onclick="remove_it()">remove last</button>
</form>
</body>
</html>
i`m working on school project
how can i access the name of variable and store it to in another variable ex: y[i].
what to write in place of comment below in javascript code.
var p = ["a","b","d"];
var q = ["d","b","c"];
var value = "d";
var x = [];
var y = [];
function testArrays(needle, arrays) {
for (var i=0; i<arrays.length; i++) {
x[i] = arrays[i].indexOf(value);
// y[i] = // store array`s name here
}
document.getElementById("demo").innerHTML = x + y;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<p>Click the button to display the position of the element "Apple":</p>
<button onclick="testArrays(value, [p, q])">Try it</button>
<p id="demo"></p>
</body>
</html>
Here is what you search for : You have to construct a object with your arrays and pass trow all the arrays.
var obj = {
p:["a","b","d"],
q: ["d","b","c"]
};
var value = "d";
var x = [];
var y = [];
function testArrays(needle, arrays) {
for(key in arrays){
x.push(arrays[key].indexOf(value));
y.push(key);
}
document.getElementById("demo").innerHTML = x + y;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<p>Click the button to display the position of the element "Apple":</p>
<button onclick="testArrays(value, obj)">Try it</button>
<p id="demo"></p>
</body>
</html>
Since you ask for what i was talking about. I'll give you the code.
Again, to re-iterate my point, you cannot get the variable name. But if you must have the variable somehow, you can work around by putting all the variables you need access to in an object.
you will not get the variable name of the object, but you can access all the properties names of this object.
Here is the codepen link to see the code running.
html
<p id="test"><p>
js
var variableList = {};
variableList.var1 = 1;
variableList.var2 = -50;
variableList.var3 = [2,4];
variableList.var4 = "4";
variableList.var5 = 5.5;
var ele = document.getElementById("test");
for(var propertyName in variableList) {
ele.innerHTML = ele.innerHTML + "<br>" + propertyName + " : " + variableList[propertyName];
}