How do I separate two svgs using raphaël? - javascript

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)

Related

plot a function then remove it with plotly.js

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>
'''

Button not calling function correctly

I am trying to call a function on a button click, but for some reason the button will not call the function. Dreamweaver does not show any syntax errors. Can anyone tell me why the button is not working?
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
</head>
<head>
<title></title>
<script type="text/javascript">
var imgObj = 0;
var imgObj1 = 0;
var animate;
var animate1;
function init(){
imgObj = document.getElementById('red');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
imgObj1 = document.getElementById('blue');
imgObj1.style.position = 'relative';
imgObj1.style.left = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left = 0) + Math.floor((Math.random() * 100) + 1) + 'px';
animate = setTimeout(moveRight(), 1000);
imgObj1.style.left = parseInt(imgObj1.style.left = 0) + Math.floor((Math.random() * 100) + 1) + 'px';
animate1 = setTimeout(moveRight(), 1000);
if (imgObj.style.left >= 1000px || imgObj1.style.left >= 1000px)
{
break;
else if
{
imgObj.style.left>= 1000
MessageBox.show("The Red Car has won the Race!");
}
else
{
MessageBox.show("The Blue Car has won the Race!");
}
}
}
</script>
</head>
<body onload = "init()">
<form>
<input type="button" value="Start" onclick="moveRight()" />
<br/><br/><br/><br><br/><br/><br/>
<img id="red" src="redcar.png" alt="Car 1"/>
<br/><br/><br/><br>
<img id="blue" src="bluecar.png" alt ="Car 2" />
</form>
</body>
</html>
Unfortunately there are so many errors that it's difficult to know where to start. The first answer to your question is that the button did nothing because your code doesn't compile. I don't know why Dreamweaver didn't report an error. Chrome's developer tools was more than happy to do so.
Here's a "working" version:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var imgObj = 0;
var imgObj1 = 0;
var animate1;
function init(){
imgObj = document.getElementById('red');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
imgObj1 = document.getElementById('blue');
imgObj1.style.position = 'relative';
imgObj1.style.left = '0px';
}
function moveRight(){
var redPosition = parseInt(imgObj.style.left);
imgObj.style.left = redPosition + Math.floor((Math.random() * 20) + 1) + 'px';
var bluePosition = parseInt(imgObj.style.left);
imgObj1.style.left = bluePosition + Math.floor((Math.random() * 20) + 1) + 'px';
if (redPosition >= 1000 || bluePosition >= 1000)
{
if (redPosition >= 1000) {
alert("The Red Car has won the Race!");
}
else
{
alert("The Blue Car has won the Race!");
}
return;
}
animate1 = setTimeout(moveRight, 50);
}
</script>
</head>
<body onload = "init()">
<form>
<input type="button" value="Start" onclick="moveRight()" />
<br/><br/><br/><br><br/><br/><br/>
<img id="red" src="redcar.png" alt="Car 1"/>
<br/><br/><br/><br>
<img id="blue" src="bluecar.png" alt ="Car 2" />
</form>
</body>
</html>

Referencing canvas with button in Javascript

Ok so I'm attempting to have a webpage with two buttons. Each of these buttons, when clicked, creates a new canvas and calls a different draw function. The first draw function would draw large circles where the users mouse is and small ones when the mouse is pressed. The other draw function does the same thing except small circles when the mouse is unpressed and large ones when it is. I'm not having a problem referencing one of these with the button but the other button doesn't seem to call its draw function. sketch2.js seems to be working fine but it seems that the draw function in sketch.js is not being called. Any advice on how I should go about fixing this is greatly appreciated!
Below is my HTML code:
<html>
<head>
<meta charset="UTF-8">
<button id="myBtn">little then big</button>
<div id="holder"></div>
<button id="myBtn2">big then little</button>
<div id="holder2"></div>
<style> body {padding: 0; margin:0;} </style>
</head>
<body>
<script type="text/javascript" src = "/Users/bburke95/Desktop/JS/p5.dom.js"> </script>
<script language="javascript" type="text/javascript" src="../p5.js"></script>
<script language="javascript" type="text/javascript" src="sketch.js"></script>
<script language="javascript" type="text/javascript" src="sketch2.js"></script>
</body>
</html>
This is my sketch.js class
btn = document.getElementById("myBtn");
var q;
btn.onclick = function setup() {
createCanvas(640, 480);
document.getElementById("holder").innerHTML = '<canvas id="myCanvas" width="490" height="220"></canvas>';
q = 1;
set = 0;
}
function draw() {
if (q == 1) {
var x;
var y;
if (mouseIsPressed) {
fill(255);
x = 160;
y = 160;
} else {
fill(0);
x = 80;
y = 80;
}
ellipse(mouseX, mouseY, x, y);
}
}
and this is my sketch2.js class
btn2 = document.getElementById("myBtn2");
var set;
btn2.onclick = function setup() {
createCanvas(640, 480);
document.getElementById("holder2").innerHTML = '<canvas id="myCanvas2" width="490" height="220"></canvas>';
set = 1;
q = 0;
}
function draw() {
if (set == 1) {
var x;
var y;
if (mouseIsPressed) {
fill(0);
x = 80;
y = 80;
} else {
fill(255);
x = 160;
y = 160;
}
ellipse(mouseX, mouseY, x, y);
}
}
If you want to run more than one P5.js processing sketches on the same page, you have to use "instance mode" to ensure that all the functions aren't cluttering the global namespace (which is a good idea anyway) so they don't overwrite one another.
From their Github project, you can instantiate new sketches like this:
var s = function( p ) {
var x = 100;
var y = 100;
p.setup = function() {
p.createCanvas(700, 410);
};
p.draw = function() {
p.background(0);
p.fill(255);
p.rect(x,y,50,50);
};
};
var myp5 = new p5(s);

Trying to use HTML5 and Javascript within Ember, Starfield component

I made a basic starfield program that loads into a canvas using javascript.
http://jsfiddle.net/vLfG2/
I've been trying to incorporate it into an ember site by putting the canvas onto a page, but I'm not sure how to load the program in. I've tried including the code into the page's router, controller, load it from a separate file, etc. Not really sure where to go from here. Any pointers?
I assume I can just use...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css">
<script src="js/libs/jquery-1.10.2.js"></script>
<script src="js/libs/handlebars-1.1.2.js"></script>
<script src="js/libs/ember-1.5.1.js"></script>
<script src="js/app.js"></script>
</script>
</head>
<body>
...
<script type="text/x-handlebars" id="starfield">
<canvas id='c'></canvas>
</script>
</body>
</html>
For the HTML.
And then...
App = Ember.Application.create({
LOG_TRANSITIONS: true
});
App.Router.map(function() {
this.route('starfield');
});
for the app file. But where do I put the star field's code?
Update
Now that I see what you're trying to do, I'd totally componentize it
App.StarFieldComponent = Em.Component.extend({
tagName:'canvas',
width: 400,
height: 300,
starCount:100,
refresh:30,
attributeBindings:['width', 'height'],
stars:null,
on:false,
build: function(){
var canvas = this.$()[0],
ctx = canvas.getContext('2d'),
stars = [],
height = this.get('height'),
width = this.get('width');
for (var i = 0, len = this.get('starCount'); i < len; i++){
stars.push([Math.random() * width, Math.random() * height, Math.random() * 2, 0.5 + Math.random() / 2]);
}
this.set('stars', stars);
this.set('ctx', ctx);
this.set('on', true);
}.on('didInsertElement').observes('starCount', 'width', 'height'),
kill: function(){
this.set('on', false);
}.on('willDestroyElement'),
clear: function () {
var ctx = this.get('ctx'),
height = this.get('height'),
width = this.get('width');
ctx.fillStyle = 'black';
ctx.clearRect(0, 0, width, height);
ctx.beginPath();
ctx.rect(0, 0, width, height);
ctx.closePath();
ctx.fill();
},
drawStars: function () {
var stars = this.get('stars'),
starCount = stars.length,
ctx = this.get('ctx');
for (var i = 0; i < starCount; i++) {
ctx.fillStyle = 'rgba(255, 255, 0, ' + stars[i][3] + ')';
ctx.beginPath();
ctx.arc(stars[i][0], stars[i][1], stars[i][2], 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
},
moveStars :function (e) {
var stars = this.get('stars'),
starCount = stars.length,
height = this.get('height'),
width = this.get('width');;
for (var i = 0; i < starCount; i++) {
if (stars[i][1] - stars[i][2] > height) {
stars[i][0] = Math.random() * width;
stars[i][2] = Math.random() * 2;
stars[i][1] = 0 - stars[i][2];
stars[i][3] = 0 + Math.random() / 2;
} else {
stars[i][1] += e;
}
}
},
gaze: function(){
if(this.get('on')){
this.loop();
}
}.observes('on'),
loop: function () {
if(!this.get('on')){
return;
}
var refreshRate = this.get('refresh');
this.clear();
this.moveStars(3);
this.drawStars();
Em.run.later(this, this.loop, refreshRate);
}
});
And then in a template you can insert remove super easily
{{star-field width=300 height=200 starCount=20}}
{{star-field width=400 height=200 starCount=500 refresh=10}}
{{star-field width=100 height=100}}
{{star-field}}
Static variables: http://emberjs.jsbin.com/yaxoweya/8/edit
Bound variables: http://emberjs.jsbin.com/yaxoweya/9/edit
Original answer (not really applicable, but good info nonetheless)
For the model, you would set up a route matching your router's name. If your route is a noun, generally you use this.resource, if it's a verb you use this.route
App = Ember.Application.create();
App.Router.map(function() {
this.resource('starfield')
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return ['red', 'yellow', 'blue'];
}
});
Route for the particular route in your app
App.StarfieldRoute = Em.Route.extend({
model:function(){
return {apple:'cow'};
}
});
Controller for wrapping your model, and interacting with the view/template
App.StarfieldController = Em.ObjectController.extend({
foo:'bar'
});
View for dom interaction
App.StarfieldView = Em.View.extend({
click: function(){
alert('you clicked this view!');
}
});
http://emberjs.jsbin.com/nodojasu/3/edit

HTML5 canvas game static solid elements

I'm writing a canvas game with easeljs. Almost everything is working correctly in this project, only problem is I can't add static objects to the field.
Here is the link my demo: http://insidejs.com/game/
I don't want to enter to the colored areas with shopping cart. Player should turn around these areas. This game illustrates what I need to do.: http://www.kokogames.com/free-games/91/racing-games/138/e-racer.htm
Thanks.
My Project:
<!DOCTYPE html>
<!--[if IE 7]> <html class="no-js ie7"> <![endif]-->
<!--[if IE 8]> <html class="no-js ie8"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="tr"><!--<![endif]-->
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Game</title>
<!-- css -->
<link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="assets/css/bootstrap-responsive.min.css" rel="stylesheet" type="text/css" />
<link href="assets/css/screen.css" rel="stylesheet" type="text/css" />
<!-- css -->
<!-- javascript -->
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script type="text/javascript" src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="assets/js/easeljs-0.6.1.min.js"></script>
<script type="text/javascript">
var CANVAS, STAGE, Shopping, GAME;
$(function () {
window.Shopping= {
Game: {}
};
GAME = Shopping.Game;
GAME = new Application();
CANVAS = document.getElementById("game");
STAGE = new createjs.Stage(CANVAS);
GAME.init();
});
var Application = function () {
};
Application.prototype = {
vehicle: null,
vehicleImg: new Image(),
map: null,
mapImg: new Image(),
TURN_FACTOR: 3,
MAX_THRUST: 1,
MAX_VELOCITY: 10,
KEYCODE_UP: 38,
KEYCODE_LEFT: 37,
KEYCODE_RIGHT: 39,
KEYCODE_DOWN: 40,
RIGHT_KEY: false,
LEFT_KEY: false,
UP_KEY: false,
DOWN_KEY: false,
map: null,
init: function () {
GAME.mapImg.src = "assets/images/map.jpg";
GAME.mapImg.name = 'map';
GAME.mapImg.onload = GAME.loadImage();
GAME.vehicleImg.src = "assets/images/vehicle.png";
GAME.vehicleImg.name = 'vehicle';
GAME.vehicleImg.onload = GAME.loadImage();
if (!createjs.Ticker.hasEventListener("tick")) {
createjs.Ticker.addEventListener("tick", GAME.tick);
}
$(document).keydown(GAME.handleKeyDown);
$(document).keyup(GAME.handleKeyUp);
},
loadImage: function () {
GAME.vehicle = new createjs.Bitmap(GAME.vehicleImg);
GAME.vehicle.x = CANVAS.width / 2;
GAME.vehicle.y = CANVAS.height / 2;
GAME.vehicle.width = 100;
GAME.vehicle.height = 69;
GAME.vehicle.regX = GAME.vehicle.width / 2;
GAME.vehicle.regY = GAME.vehicle.height / 2;
GAME.map = new createjs.Bitmap(GAME.mapImg);
GAME.map.scaleX = 1;
GAME.map.scaleY = 1;
GAME.map.width = 3000;
GAME.map.height = 2000;
GAME.map.regX = GAME.map.width / 2;
GAME.map.regY = GAME.map.height / 2;
GAME.map.x = CANVAS.width / 2;
GAME.map.y = CANVAS.height / 2 - 300;
GAME.map.speed = 0;
GAME.map.vX = 0;
GAME.map.vY = 0;
STAGE.addChild(GAME.map);
STAGE.addChild(GAME.vehicle);
STAGE.update();
},
//game listener
tick: function (event) {
if (GAME.LEFT_KEY) {
GAME.vehicle.rotation -= GAME.TURN_FACTOR;
}
if (GAME.RIGHT_KEY) {
GAME.vehicle.rotation += GAME.TURN_FACTOR;
}
if (GAME.UP_KEY) {
GAME.accelarate();
if (GAME.LEFT_KEY) {
GAME.vehicle.rotation -= 5;
}
if (GAME.RIGHT_KEY) {
GAME.vehicle.rotation += 5;
}
}
if (GAME.DOWN_KEY) {
GAME.decelerate();
if (GAME.LEFT_KEY) {
GAME.vehicle.rotation -= 5;
}
if (GAME.RIGHT_KEY) {
GAME.vehicle.rotation += 5;
}
}
STAGE.update(event);
},
handleKeyDown: function (e) {
if (!e) {
var e = window.event;
}
switch (e.keyCode) {
case GAME.KEYCODE_LEFT:
GAME.LEFT_KEY = true;
break;
case GAME.KEYCODE_RIGHT:
GAME.RIGHT_KEY = true;
break;
case GAME.KEYCODE_UP:
e.preventDefault();
GAME.UP_KEY = true;
break;
case GAME.KEYCODE_DOWN:
e.preventDefault();
GAME.DOWN_KEY = true;
break;
}
},
handleKeyUp: function (e) {
if (!e) {
var e = window.event;
}
switch (e.keyCode) {
case GAME.KEYCODE_LEFT:
GAME.LEFT_KEY = false;
break;
case GAME.KEYCODE_RIGHT:
GAME.RIGHT_KEY = false;
break;
case GAME.KEYCODE_UP:
GAME.UP_KEY = false;
break;
case GAME.KEYCODE_DOWN:
GAME.DOWN_KEY = false;
break;
}
},
accelarate: function () {
var angle = GAME.vehicle.rotation;
if (GAME.LEFT_KEY) {
angle -= 5;
}
if (GAME.RIGHT_KEY) {
angle += 5;
}
GAME.map.vX -= Math.cos(angle * Math.PI / 180) * 3;
GAME.map.vY -= Math.sin(angle * Math.PI / 180) * 3;
GAME.map.vX = Math.min(GAME.MAX_VELOCITY, Math.max(-GAME.MAX_VELOCITY, GAME.map.vX));
GAME.map.vY = Math.min(GAME.MAX_VELOCITY, Math.max(-GAME.MAX_VELOCITY, GAME.map.vY));
GAME.map.x += GAME.map.vX;
GAME.map.y += GAME.map.vY;
},
decelerate: function () {
var angle = GAME.vehicle.rotation;
if (GAME.LEFT_KEY) {
angle -= 5;
}
if (GAME.RIGHT_KEY) {
angle += 5;
}
GAME.map.vX += Math.cos(angle * Math.PI / 180) * 3;
GAME.map.vY += Math.sin(angle * Math.PI / 180) * 3;
GAME.map.vX = Math.min(GAME.MAX_VELOCITY, Math.max(-GAME.MAX_VELOCITY, GAME.map.vX));
GAME.map.vY = Math.min(GAME.MAX_VELOCITY, Math.max(-GAME.MAX_VELOCITY, GAME.map.vY));
GAME.map.x += GAME.map.vX;
GAME.map.y += GAME.map.vY;
}
//class end
};
</script>
<!-- javascript -->
</head>
<body>
<div id="page">
<canvas id="game" width="640" height="480"></canvas>
</div>
</body>
</html>
To make a collision detection work for your game you will need to make quite some changes to your project:
Currently you have one big JPG as a map, which is not a good idea, if you try to have objects collide with other objects.
1) If you are willing to split up the big JPG map(probably quickest acceptable solution): You can use one big grey JPG als the floor and place single green Bitmaps on top of that floor. Then you can use the Collision Detection suggested by #WiredPrairie (https://github.com/olsn/Collision-Detection-for-EaselJS) - doing the collision check this way should be about 3-4lines of code (+the work of splitting up your current map.jpg).
2) If you want to keep that JPG as map: I suggest you either create custom rectangles for the green areas and check every frame if the shopping cart is inside such a rectangle. Another option would be to implement a physics library like Box2D (I know, this will take some time to get into Box2D or other libraries, and I'm guessing you are looking for a quick solution, but trust me: It'll be worth it)
As a non-related hint: For projects like yours it's really worth taking a look at Box2D or other physic engines, once you get the hang of how it works, it's really a big help to use a physics library ;-)

Categories