I want to use more Javascript files on one canvas, but I can't connect them. For example I want to write a Javascript file that contains all functions and an other Javascript file which is using them.
Show me a guide, how can I make this connection?
Thanks.
This is the first javascript file :
var canvas = null;
var ctx = null;
window.onload = function () {
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
line (100,100,300,300);
}
This is the secnond file:
function line (x1,y1,x2,y2) {
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
And this is my html file:
<!DOCTYPE html>
<html>
<head>
<title>Tutorialok</title>
<script type="text/javascript" src="CanvasElement.js"></script>
<script type="text/javascript" src="line.js"></script>
<style>
#myCanvas {
border: 1px solid #9C9898;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="800" height="600">
Sorry your browser Does not support canvas element!
</canvas>
</body>
</html>
The first file cant find the second files function.
Use namespacing via Objects. I don't recommend a pattern where all functions exist in one file, but this is an idea you could use. You MUST load file1.js before file2.js can do anything.
// file1.js
window.namespace = window.namespace || {};
window.namespace.fns = {
foo: function () {}
};
// file2.js
window.namespace.fns.foo();
jsFile 1
var f1 = function(){};
var f2 = function(){}
jsFile2
var s1 = f1();
var s2 = f2();
use this on the html page
<script src="path/jsFile1.js"></script>
<script src="path/jsFile2.js"></script>
If you're expecting the function to hoist, I don't believe that would work between script files since each one is evaluated independently. Switch the script tags around so line is in scope when CanvasElement.js loads.
Otherwise, the global namespace is shared between the linked scripts.
Related
I was converting my p5js code to instance mode to run 2 canvases in the same DOM but my p5.AudioIn() function is not working. The error I get is referencing Failed to construct 'AudioWorkletNode'. I have uploaded a screenshot of the error below because it has more information about it. Why isn't AudioIn not working when converted to instance mode but works on global mode.
let s2 = function(sketch) {
sketch.quinnListenMic;
sketch.setup = function() {
let cnv = sketch.createCanvas(300, 300);
cnv.mousePressed(sketch.userStartAudio);
sketch.quinnListenMic = new p5.AudioIn(); //ERROR HERE
sketch.quinnListenMic.start();
}
sketch.draw = function() {
sketch.background(100)
sketch.micLevel = quinnListenMic.getLevel();
console.log(micLevel)
}
}
var myp5_2 = new p5(s2);
<html>
<head>
<script defer src=https://cdn.JsDelivr.net/npm/p5></script>
<script defer src=https://cdn.JsDelivr.net/npm/p5/lib/addons/p5.dom.min.js></script>
<script defer src=https://cdn.JsDelivr.net/npm/p5/lib/addons/p5.sound.min.js></script>
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.0/lib/p5.js"></script>
</head>
<body>
</body>
</html>
There were a couple of issues, fixed below with comments:
let s2 = function(sketch) {
// sketch.quinnListenMic; doesn't make sense. 1) You don't want to store your variables on the p5 instance, and 2) that statement doesn't actually do anything
// This is how you declare a local variable for use in setup/draw functions:
let quinnListenMic;
sketch.setup = function() {
let cnv = sketch.createCanvas(300, 300);
cnv.mousePressed(sketch.userStartAudio);
quinnListenMic = new p5.AudioIn(); //ERROR HERE
quinnListenMic.start();
}
sketch.draw = function() {
// Fixed local variable declaration again
// Note: there is a bug with AudioIn.getLevel not working in all browsers
let micLevel = quinnListenMic.getLevel();
// Let's not spam the console log
// console.log(micLevel)
sketch.background(sketch.map(micLevel, 0, 1, 0, 255));
}
}
var myp5_2 = new p5(s2);
<html>
<head>
<!-- Your script tags were not valid -->
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.0/lib/p5.js"></script>
<!-- For some reason p5.sound does not work with the defer attribute -->
<script src="https://cdn.jsdelivr.net/npm/p5#1.4.0/lib/addons/p5.sound.min.js"></script>
</head>
<body>
</body>
</html>
I'm very new to javascript and EaseLJS but I don't understand how this doesnt work.
I have a html file:
<!DOCTYPE html>
<html>
<head>
<script src="easeljs-0.7.1.min.js" type="text/javascript"></script>
<script src="game.s.js" type="text/javascript"></script>
<script>
function init() {
renderLevel();
}
</script>
</head>
<body onLoad="init();">
<canvas id="canvas" width="500" height="300">
alternate content
</canvas>
</body>
</html>
The game.s.js file looks like:
function renderLevel()
{
var stage = new createjs.Stage("canvas");
var bitmap = new createjs.Bitmap("brick.png");
stage.addChild(bitmap);
bitmap.x = 32;
bitmap.y = 32;
stage.update();
alert(stage.canvas);
alert(bitmap.name);
}
The alert I just put there to check the values. stage.canvas rightly points to the HTML5Canvas element but the image won't show!
What am I missing here? :)
Thank you
The problem is that you are adding the image to stage before it loads, then there's no image yet. You need to wait for the image to load before adding it to the stage.
You can do this by using a preload(); function to load all the images before calling init(); or renderLevel();. Here's what this function should look like:
function preload(images, callback) {
var count = images.length;
if (count === 0) {
callback();
}
var loaded = 0;
$(images).each(function () {
$('<img>').attr('src', this).load(function () {
loaded++;
if (loaded === count) {
callback();
}
});
});
}
...and then you can use it like so:
preload(["image1.png", "image2.png"], init());
Currently I'm play with the html5 canvas, the simple code is below:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="Scripts/jquery-2.0.3.min.js"></script>
<script>
$(function () {
//THIS WILL NOT WORK!
//var cv = $("#cv");
//THIS WORKS FINE.
var cv = document.getElementById("cv");
ct = cv.getContext("2d");
var mText = "hi";
var x = cv.width / 2;
var y = cv.height / 2;
ct.textAligh = "center";
ct.fillText(mText, x, y);
});
</script>
</head>
<body>
<div style="width:200px; height:200px; margin:0 auto; padding:5px;">
<canvas id="cv" width="200" height="200" style="border:2px solid black">
Your browser doesn't support html5! Please download a fitable browser.
</canvas>
</div>
</body>
</html>
The canvas element could only be picked by the method document.getElementById, but the jQuery method is not working. Is there a way to get the original html from the jquery object or am I miss using something?
Thanks in advance!
jQuery's $(<selector>) returns a collection of nodes (in fact it is "object masquerades as an array" as the doc says) so just use $('#cv').get(0) instead of document.getElementById("cv")
You need to use .get() following to get the actual DOM element:
var canvas = $("#cv").get(0);
Otherwise, you're getting the jQuery object when you only do $("#cv"), so methods such as getContext will not work.
using get()
http://api.jquery.com/get/
explore the jquery doc, it's very useful
I've got a button with an image inside that I want to swap when clicked. I got that part working, but now I also want it to change back to the original image when clicked again.
The code I'm using:
<button onClick="action();">click me<img src="images/image1.png" width="16px" id="ImageButton1"></button>
And the Javascript:
function action() {
swapImage('images/image2.png');
};
var swapImage = function(src) {
document.getElementById("ImageButton1").src = src;
}
Thanks in advance!
While you could use a global variable, you don't need to. When you use setAttribute/getAttribute, you add something that appears as an attrib in the HTML. You also need to be aware that adding a global simply adds the variable to the window or the navigator or the document object (I don't remember which).
You can also add it to the object itself (i.e as a variable that isn't visible if the html is viewed, but is visible if you view the html element as an object in the debugger and look at it's properties.)
Here's two alternatives. 1 stores the alternative image in a way that will cause it to visible in the html, the other doesn't.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', mInit, false);
function mInit()
{
var tgt = byId('ImageButton1');
tgt.secondSource = 'images/image2.png';
}
function byId(e){return document.getElementById(e);}
function action()
{
var tgt = byId('ImageButton1');
var tmp = tgt.src;
tgt.src = tgt.secondSource;
tgt.secondSource = tmp;
};
function action2()
{
var tgt = byId('imgBtn1');
var tmp = tgt.src;
tgt.src = tgt.getAttribute('src2');
tgt.setAttribute('src2', tmp);
}
</script>
<style>
</style>
</head>
<body>
<button onClick="action();">click me<img src="images/image1.png" width="16px" id="ImageButton1"></button>
<br>
<button onClick="action2();">click me<img id='imgBtn1' src="images/image1.png" src2='images/image2.png' width="16px"></button>
</body>
</html>
You need to store the old value in a global variable.
For example:
var globalVarPreviousImgSrc;
var swapImage = function(src)
{
var imgBut = document.getElementById("ImageButton1");
globalVarPreviousImgSrc = imgBut.src;
imgBut.src = src;
}
Then in the action method you can check if it was equal to the old value
function action()
{
if(globalVarPreviousImgSrc != 'images/image2.png')
{
swapImage('images/image2.png');
}else{
swapImage(globalVarPreviousImgSrc);
}
}
It's not a good idea to use global variables in javascripts use a closure or object literal. You can do something like using a closure
(function(){
var clickCounter = 0;
var imgSrc1 = "src to first image";
var imgSrc2 = "src to second image"
functions swapImage (src)
{
var imgBut = document.getElementById("ImageButton1");
imgBut.src = src;
}
function action()
{
if(clickCounter === 1)
{
swapImage(imgSrc1);
--clickCounter;
}else{
swapImage(imgSrc2);
++clickCounter;
}
}
})();
(I haven't run this code though)
This nice w3documentation gives you best practices.
Check this a working example just copy paste and run-
HTML
<button onClick="action();">click me<img src="http://dummyimage.com/200x200/000000/fff.gif&text=Image+1" width="200px" id="ImageButton1"></button>
JAVASCRIPT
<script>
function action()
{
if(document.getElementById("ImageButton1").src == 'http://dummyimage.com/200x200/000000/fff.gif&text=Image+1' )
document.getElementById("ImageButton1").src = 'http://dummyimage.com/200x200/dec4ce/fff.gif&text=Image+2';
else
document.getElementById("ImageButton1").src = 'http://dummyimage.com/200x200/000000/fff.gif&text=Image+1';
}
</script>
Check this working example - http://jsfiddle.net/QVRUG/4/
I would like to preload the SWF before showing them to the user.
SWF are dynamic and I dont have the FLA files.
I would love to do it using Javascript or jquery if possible.
Have a look at swfjsPreLoader:
This preloader accepts an array of assets (jpg,gif,png,swf) you would
like to preload. Internally it will create an flash-application which
does the preloading. You could define several callback handlers. So
JavaScript gets to know when all assets are loaded or each single
asset is loaded including SWF-files.
I don't know if you're still looking for answers, but here it is.
Create two divs inside your page. Give one an ID called loading, and another the id feature, and hide feature. Put your flash content inside feature, and make sure to hide feature with css display:none.
Then, at the top of your page, or wherever you do your onload stuff, do this:
$(document).load('/path/to/your.swf', function() {
$('#feature').slideDown(600);
$('#loader').slideUp(300);
});
And there you have it.
Inside loading, you can put one of those happy little spinning wheel graphics. I'm sure there are more sophisticated things you can do with callbacks, but this will do the job of preloading.
Enjoy.
You can first load swf file via ajax and then add object to dom.
In this way, browser will use cache, swf is reloaded from cache and is immediately ready.
Follow a sample of what I'm saying (I cannot give you a fiddle sample because you need a local swf to be ajax loaded).
swfobject can be used in "loadObject" function for a better configuration of swf object.
"mySwfFunction" is called after swf is loaded. It can be removed if not needed.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Swf demo</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>
<style type='text/css'>
</style>
<script type='text/javascript'>
$(window).load(function () {
var loader = new
function () {
var loadObject = function ($el, src, callback, width, height) {
var d = document;
var s = 'object';
var obj = d.createElement(s);
obj.type = 'application/x-shockwave-flash';
if(width){
obj.width = width.toString() + 'px';
}
obj.name = 'plugin';
if(height){
obj.height = height.toString() + 'px';
}
obj.data = src;
$el[0].appendChild(obj);
};
this.loadSwf = function ($el, src, callback, width, height) {
$.ajax({
url: src,
success: function (data) {
loadObject($el, src, callback, width, height);
if(callback) callback();
},
error: function (xhr) {
//your error code
}
});
};
} ();
var mySwfCallback = function() {
$('#mySwf').show();
}
var $el = $('#mySwf');
var src = 'your_file_url.swf';
loader.loadSwf($el, src, mySwfCallback, 300, 300);
});
</script>
</head>
<by>
<div id='mySwf' style='display:none;' >
</div>
</body>
</html>
Can you preload the whole page? If so here is an idea with jQuery:
http://www.gayadesign.com/scripts/queryLoader/
Personally I think it's best to use a Flash-based polite loader as this can be as little as 5kb. The code for it doesn't have to be that hard, something along the lines of:
package
{
import com.firestartermedia.lib.as3.utils.DisplayObjectUtil;
import flash.display.Sprite;
import flash.events.Event;
[SWF( backgroundColor=0xFFFFFF, frameRate=30, height=400, width=600 )]
public class AppLoader extends Sprite
{
public function AppLoader()
{
loaderInfo.addEventListener( Event.INIT, handleInit );
}
private function handleInit(e:Event):void
{
loaderInfo.removeEventListener( Event.INIT, handleInit );
DisplayObjectUtil.loadMovie( 'App.swf', null, handleComplete );
}
private function handleComplete(e:Event):void
{
removeChild( loader );
addChild( e.target.content );
}
}
}
This uses the DisplayObjectUtil available on github: https://github.com/ahmednuaman/as3
Use another swf with preloader. Look here:
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7de1.html