I am trying to implement the handleOnPress function, the code is provided by the textbook which is confusing because it doesn't seem to be working as expected, in fact it does nothing.
The function is supposed to allow me to click the squares in the memory game, if the squares are the same color both of the chosen squares disappear, if you click on the same square twice the function resets and if you match two that aren't the same the function resets.
It would be really appreciated if anyone can take a look and point out any errors they see, thank you!
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var squareSide = 70;
var squareOutline = 5;
var max_rgb_color_number = 255;
var gray = createjs.Graphics.getRGB(20, 20, 20);
var placementArray = [];
var highlight = createjs.Graphics.getRGB(255, 255, 0);
var tileClicked;
function init() {
var rows = 6;
var columns = 6;
var squarePadding = 10;
canvas = document.getElementById('myCanvas');
stage = new createjs.Stage(canvas);
var numberOfTiles = rows*columns;
setPlacementArray(numberOfTiles);
for(var i=0;i<numberOfTiles;i++){
var placement = getRandomPlacement(placementArray);
if(i % 2 === 0){
var color = randomColor();
}
square = drawSquare(color);
square.color = color;
square.x = (squareSide+squarePadding) * (placement%columns);
square.y = (squareSide+squarePadding) * Math.floor(placement/columns);
stage.addChild(square);
square.onPress = handleOnPress;
stage.update();
}
}
function drawSquare(color) {
var shape = new createjs.Shape();
var graphics = shape.graphics;
graphics.setStrokeStyle(squareOutline);
graphics.beginStroke(gray);
graphics.beginFill(color);
graphics.rect(squareOutline, squareOutline, squareSide, squareSide);
return shape;
}
function randomColor(){
var color = Math.floor(Math.random()*max_rgb_color_number);
var color2 = Math.floor(Math.random()*max_rgb_color_number);
var color3 = Math.floor(Math.random()*max_rgb_color_number);
return createjs.Graphics.getRGB(color, color2, color3);
}
function setPlacementArray(numberOfTiles){
for(var i=0;i<numberOfTiles;i++){
placementArray.push(i);
}
}
function getRandomPlacement(placementArray){
randomNumber = Math.floor(Math.random()*placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event){
var tile = event.target;
if(!!tileClicked === false){
tile.graphics.setStrokeStyle(squareOutline).beginStroke(highlight)
.rect(squareOutline, squareOutline, squareSide, squareSide);
tileClicked = tile;
}
else{
if(tileClicked.color === tile.color && tileClicked !== tile){
tileClicked.visible = false;
tile.visible = false;
}
else{
tileClicked.graphics.setStrokeStyle(squareOutline).beginStroke(gray)
.rect(squareOutline, squareOutline, squareSide, squareSide);
}
tileClicked = null;
}
stage.update();
}
</script>
</head>
<body onload="init()">
<canvas id="myCanvas" width="960" height="600"></canvas>
</body>
</html>
The onEvent-style handlers (onClick, onMouseDown, etc) were deprecated and removed a long time ago (Version 0.7.0, September 25, 2013).
Instead, use events, such as
square.addEventListener("mousedown", handleOnPress);
or the shortcut on() method:
square.on("mousedown", handleOnPress);
Note also there is no "press" event. There is a "mousedown" event, as well as "pressmove"/"pressup" events for drag and drop-style events.
Here is a listing of events on all display objects: https://createjs.com/docs/easeljs/classes/DisplayObject.html#event_mousedown
I don't know if this will solve everything, but it should get your click handlers firing.
Related
this is my first question here!
im trying to make a website that show videos that i make and i want my viewers can see a preview of video when they hover mouse on the a element or element .
i just do it but i have some problems and questions. lemme show you code example first and then i ask my questions.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="thumbs" style="width:216px;height:468px;border: 5px solid blue;background-color:red;"><canvas onmouseover="getid1(this);" onmouseout="getid2(this);" id="canvas1"></canvas></div>
<script>
var thumbsList = [];
var delay = 100;
var i = 0;
var video = document.createElement("video");
var a = 0;
var m = document.getElementById("canvas1");
var mtx = m.getContext("2d");
var generate = true;
var animstop = false;
var vidFrames = 64;
m.width = 216;
m.height = 468;
video.preload = "auto";
video.src = "aaaa.mp4";
function stranim(bb){
if(generate){
animstop = false;
video.currentTime = i;
generateVid();
generate = false;
}else{
animstop = false;
startAnim();
}
}
function stpanim(bb) {
clearTimeout();
animstop = true;
mtx.drawImage(thumbsList[0], 0, 0);
}
// if i replace this section with generateVid() the code is working
/*video.addEventListener('seeked', function() {
var d = (video.duration / vidFrames) * 2;
generateThumbnail();
i += video.duration / vidFrames;
if (i <= video.duration) {
video.currentTime = i;
generateVid()
if(d == i){
startAnim();
}
}
});*/
function generateVid() {
var d = (video.duration / vidFrames) * 2;
generateThumbnail();
i += video.duration / vidFrames;
if (i <= video.duration) {
video.currentTime = i;
generateVid();
if(d == i){
startAnim();
}
}
}
function generateFirstThumbnail() {
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
c.width = 216;
c.height = 468;
ctx.drawImage(video, 0, 0, 216, 468);
thumbsList.push(c);
thumbs.appendChild(m);
mtx.drawImage(thumbsList[0], 0, 0);
i += video.duration / vidFrames;
}
function generateThumbnail() {
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
c.width = 216;
c.height = 468;
ctx.drawImage(video, 0, 0, 216, 468);
thumbsList.push(c);
}
function startAnim() {
var currentFrame = 0;
function anim() {
if(currentFrame != (vidFrames - 1) && animstop == false){
currentFrame = (currentFrame + 1) % thumbsList.length;
mtx.drawImage(thumbsList[currentFrame], 0, 0);
setTimeout(anim, delay);
}
}
anim();
}
function getid1(obj) {
stranim(obj.id)
}
function getid2(obj) {
stpanim(obj.id)
}
window.onload = function(){
generateFirstThumbnail();
};
</script>
</body>
</html>
the questions are :
1- why my generatevid() function is not working? this function is just like that eventlistener.
2- i want to add this code on a class to use it on multiple videos but idk how and i think this cant be done with js classes.( i search so many sites for it)
3-i can use 2d arrays for saving my video previews but is it dont make my site lower on load speed or it dont fill the ram of user?
4-there is any way that i make this code better and easyer?(i dont want to use jquery for no reason).
For a pure js approach you can check this not mine btw: https://codepen.io/tepexic/pen/BazYgJe
html:
<input type="file" accept="video/*" id="input-tag"/>
<hr>
<video controls id="video-tag">
<source id="video-source" src="splashVideo">
Your browser does not support the video tag.
</video>
JS
const videoSrc = document.querySelector("#video-source");
const videoTag = document.querySelector("#video-tag");
const inputTag = document.querySelector("#input-tag");
inputTag.addEventListener('change', readVideo)
function readVideo(event) {
console.log(event.target.files)
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
console.log('loaded')
videoSrc.src = e.target.result
videoTag.load()
}.bind(this)
reader.readAsDataURL(event.target.files[0]);
}
}
But for other approach i would probably use http://ffmpeg.org/ library to generate a preview video (e.g 10 seconds video) and https://videojs.com library for video player so you have a control when user hover the player.
I just did some test on your code, your video is getting seeked only once. No event is raised after that, which means your thumbnail will remain same.
Here is how I was able to fix it
function generateVid() {
var d = (video.duration / vidFrames) * 2;
generateThumbnail();
i += video.duration / vidFrames;
if (i <= video.duration) {
video.currentTime = i;
console.log("starting seeking");
if(d == i){
startAnim();
}
}
}
video.onseeked = (event) => {
if (animstop == false)
{
setTimeout(generateVid, delay);
}
console.log("seeked");
};
currelty working on a small matching puzzle game. Currently it displays text for the time remaining and the number of tiles that have been macthes. I'm trying to create on for best completion time as well (How fast the person finishes the game) however have been running into a lot of problems. for two variables that I created "txt" and "matchesFoundText" when I type them the autocomplete box will popup and ".text" is displayed as one of the options so i would get something like "txt.text. however I'm not getting that option at all for "bestTimeTxt" and I have no idea as to why this is happening. I did all three variables the same way so I'm at a loss as to why Text is not available to select from for "bestTimeTxt". Here is my entire script.
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var squareSide = 70;
var squareOutline = 5;
var max_rgb_color_value = 255;
var gray = Graphics.getRGB(20, 20, 20);
var placementArray = [];
var tileClicked;
var timeAllowable;
var totalMatchesPossible;
var matchesFound;
var txt;
var bestTime;
var bestTimeTxt;
var matchesFoundText;
var squares;
function init() {
var rows = 5;
var columns = 6;
var squarePadding = 10;
canvas = document.getElementById('myCanvas');
stage = new Stage(canvas);
var numberOfTiles = rows*columns;
matchesFound = 0;
timeAllowable = 5;
bestTime = 0;
txt = new Text(timeAllowable, "30px Monospace", "#000");
txt.textBaseline = "top"; // draw text relative to the top of the em box.
txt.x = 500;
txt.y = 0;
bestTimeTxt = new Text(bestTime, "30px Monospace", "#000");
bestTimeTxt.textBaseLine = "top";
bestTimeTxt.x = 500;
bestTimeTxt.y = 80;
stage.addChild(txt);
stage.addChild(bestTimeTxt);
squares = [];
totalMatchesPossible = numberOfTiles/2;
Ticker.init();
Ticker.addListener(window);
Ticker.setPaused(false);
matchesFoundText = new Text("Pairs Found: "+matchesFound+"/"+totalMatchesPossible, "30px Monospace", "#000");
matchesFoundText.textBaseline = "top"; // draw text relative to the top of the em box.
matchesFoundText.x = 500;
matchesFoundText.y = 40;
stage.addChild(matchesFoundText);
setPlacementArray(numberOfTiles);
for(var i=0;i<numberOfTiles;i++){
var placement = getRandomPlacement(placementArray);
if (i % 2 === 0){
var color = randomColor();
}
var square = drawSquare(gray);
square.color = color;
square.x = (squareSide+squarePadding) * (placement % columns);
square.y = (squareSide+squarePadding) * Math.floor(placement / columns);
squares.push(square);
stage.addChild(square);
square.cache(0, 0, squareSide + squarePadding, squareSide + squarePadding);
square.onPress = handleOnPress;
stage.update();
};
}
function drawSquare(color) {
var shape = new Shape();
var graphics = shape.graphics;
graphics.setStrokeStyle(squareOutline);
graphics.beginStroke(gray);
graphics.beginFill(color);
graphics.rect(squareOutline, squareOutline, squareSide, squareSide);
return shape;
}
function randomColor(){
var color = Math.floor(Math.random()*255);
var color2 = Math.floor(Math.random()*255);
var color3 = Math.floor(Math.random()*255);
return Graphics.getRGB(color, color2, color3)
}
function setPlacementArray(numberOfTiles){
for(var i = 0;i< numberOfTiles;i++){
placementArray.push(i);
}
}
function getRandomPlacement(placementArray){
randomNumber = Math.floor(Math.random()*placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event){
var tile = event.target;
tile.graphics.beginFill(tile.color).rect(squareOutline, squareOutline, squareSide, squareSide);
if(!!tileClicked === false || tileClicked === tile){
tileClicked = tile;
tileClicked.updateCache("source-overlay");
}else{
if(tileClicked.color === tile.color && tileClicked !== tile){
tileClicked.visible = false;
tile.visible = false;
matchesFound++;
matchesFoundText.text = "Pairs Found: "+matchesFound+"/"+totalMatchesPossible;
if (matchesFound===totalMatchesPossible){
gameOver(true);
}
}else{
tileClicked.graphics.beginFill(gray).rect(squareOutline, squareOutline, squareSide, squareSide);
}
tileClicked.updateCache("source-overlay");
tile.updateCache("source-overlay");
tileClicked = tile;
}
stage.update();
}
function tick() {
secondsLeft = Math.floor((timeAllowable-Ticker.getTime()/1000));
txt.text = secondsLeft;
;
if (secondsLeft <= 0){
gameOver(false);
}
stage.update();
}
function gameOver(win){
Ticker.setPaused(true);
for(var i=0;i<squares.length;i++){
squares[i].graphics.beginFill(squares[i].color).rect(5, 5, 70, 70);
squares[i].onPress = null;
if (win === false){
squares[i].uncache();
}
}
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play Again?</a>";
if (win === true){
matchesFoundText.text = "You win!"
}else{
txt.text = secondsLeft + "... Game Over";
}
}
function replay(){
init();
}
</script>
</head>
<body onload="init()">
<header id="header">
<p id="replay"></p>
</header>
<canvas id="myCanvas" width="960" height="400"></canvas>
</body>
</html>
Okay so apparently the reason why I was having issues is because the x and y positions of the bestTimeTxt variable was causing it to be obscured by the position of everything else.
I have created a small test project to replicate the problem.
The project contains only pixi.min.js and index.html with code from this example:
http://pixijs.github.io/examples/index.html?s=demos&f=interactivity.js&title=Interactivity
Buttons work when I test it via the browser.
They also work in the intel-xdk emulate tab.
But when I go to test tab, push files, scan QR code to open the created app on the iphone, the buttons appear but touch events are not working.
Why are the touch events not firing on the iPhone?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body style="margin:0; padding: 0; background: #333333;">
<script src="pixi.min.js"></script>
<script>
var renderer = PIXI.autoDetectRenderer(800, 600);
document.body.appendChild(renderer.view);
var stage = new PIXI.Container();
var textureButton = PIXI.Texture.fromImage('images/button.png');
var textureButtonDown = PIXI.Texture.fromImage('images/button.png');
var textureButtonOver = PIXI.Texture.fromImage('images/button2.png');
var buttons = [];
var buttonPositions = [
175, 75,
655, 75,
410, 325,
150, 465,
685, 445
];
var noop = function () {
//console.log('click');
};
for (var i = 0; i < 5; i++)
{
var button = new PIXI.Sprite(textureButton);
button.buttonMode = true;
button.anchor.set(0.5);
button.position.x = buttonPositions[i*2];
button.position.y = buttonPositions[i*2 + 1];
button.interactive = true;
button.on('mousedown', onButtonDown)
.on('touchstart', onButtonDown)
.on('mouseup', onButtonUp)
.on('touchend', onButtonUp)
.on('mouseupoutside', onButtonUp)
.on('touchendoutside', onButtonUp)
.on('mouseover', onButtonOver)
.on('mouseout', onButtonOut);
button.tap = noop;
button.click = noop;
stage.addChild(button);
buttons.push(button);
}
buttons[0].scale.set(1.2);
buttons[2].rotation = Math.PI / 10;
buttons[3].scale.set(0.8);
buttons[4].scale.set(0.8,1.2);
buttons[4].rotation = Math.PI;
animate();
function animate() {
renderer.render(stage);
requestAnimationFrame(animate);
}
function onButtonDown(){
this.isdown = true;
this.texture = textureButtonDown;
this.alpha = 1;
}
function onButtonUp(){
this.isdown = false;
if (this.isOver){ this.texture = textureButtonOver;
}else{ this.texture = textureButton; }
}
function onButtonOver(){
this.isOver = true;
if (this.isdown){
return;
}
this.texture = textureButtonOver;
}
function onButtonOut(){
this.isOver = false;
if (this.isdown){ return; }
this.texture = textureButton;
}
</script>
</body>
</html>
var textureButton = PIXI.Texture.fromImage('images/button.png');
var textureButtonDown = PIXI.Texture.fromImage('images/button.png');
var textureButtonOver = PIXI.Texture.fromImage('images/button2.png');
It is working on iPhone, but you are not seeing anything happen cause you have the initial button image textureButton and textureButtonDown same (button.png). So you are not seeing any difference on screen when u touch on it. On iPhone there is no hover event for touch event, so the textureButtonOver is not applied
But when u test on emulator, you are using mouse, so when u move the mouse over the button textureButtonOver is applied and u see a change on screen.
So change the textureButtonDown to a different image (button3.png) and u will see it work on iPhone
edit: SOLVED
I'm a highschool student in Japan trying to learn how to program.
I recently viewed https://vimeo.com/105955605 this video, and decided I could use the beginning section to start building pong in javascript.
I'm pretty much a complete novice with programming and/or javascript and I still have a long way to go.
I got Player1 (left paddle) to work on its own, so I figured I could just copy paste, mess with a couple things, and make Player2. However, now Player2 moves when I press w/s, but Player1 no longer moves.
I've tried creating 2 separate keyboarder() functions, using this.keyboarder from Player1 in player2 (Player2.keyboarder = Player1.keyboarder() ), and declaring/calling keyboarder() before doing anything else.
HTML:
<html>
<head>
<meta charset="UTF-8">
<title>Pong</title>
<link type="text/css" rel="stylesheet" href="css/stylesheet.css">
</head>
<body>
<canvas id="screen" width="310" height="210"></canvas>
<script src="js/pong.js"></script>
</body>
</html>
JavaScript:
;(function(){
//Main game function
//tells objects in bodies array to update.
//stores gameSize pulled from canvasId
var Game = function(canvasId){
var canvas = document.getElementById(canvasId);
var screen = canvas.getContext('2d');
var gameSize = {x: canvas.width, y: canvas.height};
var self = this;
//bodies array
this.bodies = [new Player1(this, gameSize), new Player2(this, gameSize)];
//update function
var tick = function(){
self.update();
self.draw(screen,gameSize);
requestAnimationFrame(tick);
};
tick();
};
//constructer for game() function. tells bodies to update, and draw
Game.prototype = {
update: function(){
for(var i =0 ; i < this.bodies.length; i++){
this.bodies[i].update();
}
},
draw:function(screen,gameSize){
screen.clearRect(0,0,gameSize.x,gameSize.y);
for(var i =0 ; i < this.bodies.length; i++){
drawRect(screen, this.bodies[i]);
}
}
};
//P1 object, declares size and start position of P1
var Player1= function(game, gameSize){
this.size = {x:30,y:gameSize.y / 3};
this.game = game;
this.gameSize = gameSize;
this.center = {x: 0, y:gameSize.y/2};
this.keyboarder = new Keyboarder();
requestAnimationFrame(this.update);
};
//constructor for P1, updates position based on keyboard input
Player1.prototype = {
update:function(){
if (this.keyboarder.isDown(this.keyboarder.KEYS.DOWN) && this.center.y < (5*this.gameSize.y / 6)){
this.center.y += 4;
}else if(this.keyboarder.isDown(this.keyboarder.KEYS.UP) && this.center.y > this.size.y /2 ){
this.center.y -= 4;
}
}
};
//P2, same as P1 aside from position
var Player2= function(game, gameSize){
this.size = {x:30,y:gameSize.y / 3};
this.game = game;
this.gameSize = gameSize;
this.center = {x: gameSize.x, y:gameSize.y/2};
this.keyboarder = new Keyboarder();
requestAnimationFrame(this.update);
};
//constructor for P2, same as P1
Player2.prototype = {
update:function(){
if (this.keyboarder.isDown(this.keyboarder.KEYS.S) && this.center.y < (5*this.gameSize.y / 6)){
this.center.y += 4;
}else if(this.keyboarder.isDown(this.keyboarder.KEYS.W) && this.center.y > this.size.y /2 ){
this.center.y -= 4;
}
}
};
//Draw function, draws object
var drawRect = function(screen, body){
screen.fillRect(body.center.x - body.size.x /2,
body.center.y - body.size.y /2, body.size.x,body.size.y);
};
//Keyboard input function
//reads if keys are being pressed and takes the event code
//isDown() returns boolean of key down = true, key up = false
var Keyboarder = function(
){
var keyState = {};
window.onkeydown = function(e){
keyState[e.keyCode] = true;
};
window.onkeyup = function(e){
keyState[e.keyCode] = false;
};
this.KEYS = {DOWN: 37, UP:39,W:87 , S: 83};
this.isDown = function(keyCode){
return keyState[keyCode] === true;
};
};
//calls game() function when the page has loaded.
window.onload = function(){
new Game("screen")
};
})();
Sorry if this is bad protocol for using stackoverflow, I'm also new to asking questions here.
The problem is you have two Keyboarder instances, and they're both binding to the key events by assigning a handler directly to them - this will overwrite any other handlers. There's two ways to fix it:
1: Don't assign directly, instead use addEventListener, eg:
window.addEventListener('keydown', function(e){
keyState[e.keyCode] = true;
});
2: Use the same keyboarder instance for both players:
var kb = new Keyboarder();
this.bodies = [new Player1(this, gameSize, kb), new Player2(this, gameSize, kb)];
and in your player object assign it to this 3rd parameter. Even if you go this route, I would still advise on using addEventListener as well simply to ensure that the events can be bound to in multiple places if needed.
On another point, you should also be able to refactor your players into a single function and create two instances of it with different parameters, but that sort of thing is better dealt with over on Code Review.
When you create two Keyboarder instances, one collides with the other, because of this:
window.onkeydown = function(e){
keyState[e.keyCode] = true;
};
window.onkeyup = function(e){
keyState[e.keyCode] = false;
};
When you create one Keyboarder, the event listeners the previous one attached are overriden. Try something like this:
window.addEventListener('keydown', function(e){
keyState[e.keyCode] = true;
});
window.addEventListener('keyup', function(e){
keyState[e.keyCode] = false;
});
This ensures there are listeners for every instance of the Keyboarder.
I want to call the function upon the onmouseover="ParentFunction();" then kill it onmouseout="killParent();".
Note: in my code the parent function is called initiate(); and the killer function is called reset(); which lies outside the parent function at the bottom of the script.
I don't know how to kill the intitiate() function my first guess was:
var reset = function(){
return initiate();
};
here's my source code: any suggestions and help appreciated.
<!doctype html>
<html>
<head>
<title> function/event prototype </title>
<link rel="stylesheet" type="text/css" href="styling.css" />
</head>
<body>
<h2> <em>Fantastical place<br/>prototype</em> </h2>
<div id="button-container">
<div id="button-box">
<button id="activate" onmouseover="initiate()" onmouseout="reset();" width="50px" height="50px" title="Activate"> </button>
</div>
<div id="text-box">
</div>
</div>
<div id="container">
<canvas id="playground" width="200px" height="250px">
</canvas>
<canvas id="face" width="400px" height="200px">
</canvas>
<!-- <div id="clear"> </div> -->
</div>
<script>
alert("Welcome, there are x entries as of" +""+new Date().getHours());
//global scope
var i=0;
var c1 = []; //c is short for collect
var c2 = [];
var c3 = [];
var c4 = [];
var c5 = [];
var c6 = [];
var initiate = function(){ //the button that triggers the program
var timer = setInterval(function(){clock()},90); //copy this block for ref.
function clock(){
i+=1;
var a = Math.round(Math.random()*200);
var b = Math.round(Math.random()*250);
var c = Math.round(Math.random()*200);
var d = Math.round(Math.random()*250);
var e = Math.round(Math.random()*200);
var f = Math.round(Math.random()*250);
c1.push(a);
c2.push(b);
c3.push(c);
c4.push(d);
c5.push(e);
c6.push(f);
// document.write(i);
var c = document.getElementById("playground");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(c3[i-2], c4[i-2]);
ctx.bezierCurveTo(c1[i-2],c2[i-2],c5[i-2],c6[i-2],c3[i-1], c4[i-1]);
// ctx.lineTo(c3[i-1], c4[i-1]);
if(a<200){
ctx.strokeStyle="#FF33CC";
}
else if(a<400){
ctx.strokeStyle="#FF33aa";
}
else{
ctx.strokeStyle="#FF3388";
}
ctx.stroke();
document.getElementById("text-box").innerHTML=i+"<p>Thoughts.</p>";
if(i===20){
//alert("15 reached");
clearInterval(timer);//to clearInterval must be using a global scoped variable.
return;
}
}; //end of clock
//setInterval(clock,150);
var targetFace = document.getElementById("face");
var face = targetFace.getContext("2d");
var faceTimer = setInterval(function(){faceAnim()},80); //copy this block for ref. global scoped.
function faceAnim(){
face.beginPath();
face.strokeStyle="#FF33CC";
face.moveTo(100,104); //eye line
face.bezierCurveTo(150,125,250,125,300,104);
face.moveTo(200,1); //centre line
face.lineTo(200,400);
face.moveTo(125,111);//left eye lid
face.bezierCurveTo(160,135,170,130,185,120);
face.moveTo(150,116);//left eye
face.bezierCurveTo(155,125,165,125,170,118);
face.moveTo(275,111);//right eye lid
face.bezierCurveTo(240,135,230,130,215,120);
face.moveTo(250,116);//right eye
face.bezierCurveTo(245,125,235,125,230,118);
face.moveTo(195, 118); //left nose
face.lineTo(190, 160);
face.lineTo(200,170);
face.moveTo(190,160); //left nostroll
face.lineTo(180,160);
face.lineTo(191,154);
face.moveTo(180,160); //left lower nostrol
face.lineTo(200,170);
face.moveTo(205, 118); //right nose
face.lineTo(210, 160);
face.lineTo(200,170);
face.moveTo(210,160); //right nostroll
face.lineTo(220,160);
face.lineTo(209,154);
face.moveTo(220,160); //right lower nostrol
face.lineTo(200,170);
face.moveTo(200,140); //outer triad
face.lineTo(170, 100);
face.lineTo(230, 100);
face.lineTo(200, 140);
face.moveTo(200,145); //outer triad drop shadow
face.lineTo(170, 100);
face.lineTo(230, 100);
face.lineTo(200, 145);
face.moveTo(200,130); //inner triad
face.lineTo(180, 105);
face.lineTo(220, 105);
face.lineTo(200, 130);
//face.lineWidth =0.6;
face.moveTo(280,111);//outer right eye lid
face.bezierCurveTo(240,140,230,135,210,120);
face.moveTo(120,111);//outer left eye lid
face.bezierCurveTo(160,140,170,135,190,120);
face.moveTo(162,174); //upper mouth line
face.bezierCurveTo(170,180,230,180,238,174);
face.moveTo(165,175); //mouth line bottom
face.bezierCurveTo(190,Math.floor(Math.random()*25+180),210,Math.floor(Math.random()*25+180),235,175);
face.moveTo(232,204); //head shape
face.lineTo(340, 20);
face.moveTo(168,204); //head shape
face.lineTo(60, 20);
face.stroke(); //exicute all co-ords.
}; //end of face anim
var clearFace = function(){
document.getElementById('face').getContext('2d').clearRect(0, 0, 700, 750);
};
setInterval(clearFace,90);
}; //end of parent function
var reset = function(){
document.getElementById('playground').getContext('2d').clearRect(0, 0, 700, 750);
//clearInterval(faceTimer);
//delete initiate();
};
</script>
</body>
</html>
Set a variable in reset() e.g. stop = true;
Then check it in faceTimer or anyplace else...
Overall the structure should be this though,
///Globals
var queue = [], stop = false;
// drawing function ....
function draw(){
if(stop || !Boolean(queue) || !Boolean(queue.length)) return;
var current = undefined;
while(Boolean(current = queue.pop()))
{
if(!stop){
current();
var nextTime = Number(current.nextInterval);
if(nextTime > 0) setTimeout(nextTime , draw || this);
}
else if(Boolean(current.shouldBreak)) break;
}
}
where current is a function which has been queued to do the drawing from faceTimer
e.g.
var work = function(){ clock(); faceAnim(); queue.push(this); }; work.nextInterval = 500; work.shouldBreak = false; queue.push(work);
Then initiate becomes var initiate = work; initiate();;
I have your example working # http://jsfiddle.net/JtHQ4/18/