Calling and killing a parent function with onmouseover and onmouseout events - javascript

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/

Related

Difficulty implementing handleOnPress function

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.

repaint canvas onclick event using Teechart

I have a sample code here to draw randomly generated signal on a canvas using Teechart. I have defined 2 canvas sections. One is generating the signal for 10000 samples. Whereas second canvas bar is depicting the preview of the main canvas. However, I do not want that preview to be displayed on 2nd canvas which is also a works as a scrollbar.
My second question is is it possible to repaint the canvas on the scrollbar when I move the ranger from one sample of the canvas bar to other. In simple words when I scroll across the scroller which is the second canvas.
I have added a mock-up, where it shows how the color on the bar has marked in blue showing that segment on the progress bar is been viewed. when the entire chart is scrolled the whole progress bar will turn to blue colour.
var Chart1, scroller;
function draw() {
Chart1 = new Tee.Chart("canvas");
Chart1.addSeries(new Tee.Area()).addRandom(10000).format.shadow.visible = false;
Chart1.addSeries(new Tee.Line()).addRandom(10000);
Chart1.title.text = "Chart Scroller";
Chart1.panel.transparent = true;
Chart1.legend.visible = false;
Chart1.axes.bottom.setMinMax(200, 499);
Chart1.zoom.enabled = false;
Chart1.scroll.mouseButton = 0;
Chart1.cursor = "pointer";
Chart1.scroll.direction = "horizontal";
scroller = new Tee.Scroller("canvas2", Chart1);
scroller.onChanging = function(s, min, max) {
document.getElementById("data").textContent = "Showing data from " + min.toFixed(0) + " to " + max.toFixed(0);
}
// changeTheme(Chart1, "minimal");
Chart1.draw();
}
<script src="https://www.steema.com/files/public/teechart/html5/latest/src/teechart.js"></script>
<script src="https://www.steema.com/files/public/teechart/html5/latest/src/teechart-extras.js"></script>
<body onload="draw()">
<div class="x_content">
<br><canvas id="canvas" width="600" height="400">
This browser does not seem to support HTML5 Canvas.
</canvas>
<br/>
<canvas id="canvas2" width="550" height="80" style="margin-left : 55px;">
This browser does not seem to support HTML5 Canvas.
</canvas>
<br/>
<input type="checkbox" id="range" onclick="scroller.useRange(this.checked);" checked>Range
<input type="checkbox" id="invert" onclick="scroller.invertThumb(this.checked);">Inverted
<br/>
<span id="data" />
</div>
</body>
Could someone please help me?
You can clear the .scroller.onDrawThumb function to skip drawing the series in the scroller.
scroller.scroller.onDrawThumb = "";
Regarding the second question, you could store the viewed sections in an array (ie history) and use it to draw blue rectangles at a custom onDrawThumb function.
Here a working example:
var Chart1, scroller;
function draw() {
Chart1 = new Tee.Chart("canvas");
Chart1.addSeries(new Tee.Area()).addRandom(10000).format.shadow.visible = false;
Chart1.addSeries(new Tee.Line()).addRandom(10000);
Chart1.title.text = "Chart Scroller";
Chart1.panel.transparent = true;
Chart1.legend.visible = false;
Chart1.axes.bottom.setMinMax(200, 499);
Chart1.zoom.enabled = false;
Chart1.scroll.mouseButton = 0;
Chart1.cursor = "pointer";
Chart1.scroll.direction = "horizontal";
scroller = new Tee.Scroller("canvas2", Chart1);
var history = [];
scroller.onChanging = function(s, min, max) {
document.getElementById("data").textContent = "Showing data from " + min.toFixed(0) + " to " + max.toFixed(0);
var done = false;
history.forEach(function(item) {
if (!done) {
if ((min >= item[0]) && (min <= item[1])) {
item[1] = Math.max(item[1], max);
done = true;
} else if ((max >= item[0]) && (max <= item[1])) {
item[0] = Math.min(item[0], min);
done = true;
}
}
});
if (!done) history.push([min, max]);
};
Chart1.draw();
scroller.scroller.onDrawThumb = "";
scroller.scroller.onDrawThumb = function(s) {
var f = new Tee.Format(scroller),
b = scroller.scroller.bounds,
c = scroller.target,
li = c.series,
h, v;
f.fill = "RGB(74, 144, 226)";
f.stroke.fill = "";
function saveAxis(axis, data) {
var res = {
mi: axis.minimum,
ma: axis.maximum,
sp: axis.startPos,
ep: axis.endPos
}
restoreAxis(axis, data);
return res;
}
function restoreAxis(axis, old) {
axis.minimum = old.mi;
axis.maximum = old.ma;
axis.startPos = old.sp;
axis.endPos = old.ep;
axis.scale = (old.ep - old.sp) / (old.ma - old.mi);
}
h = saveAxis(c.axes.bottom, {
sp: b.x,
ep: b.x + b.width,
mi: li.minXValue(),
ma: li.maxXValue()
});
history.forEach(function(item) {
var x1 = c.axes.bottom.calc(item[0]);
var x2 = c.axes.bottom.calc(item[1]);
var y1 = scroller.chartRect.y;
var y2 = y1 + scroller.chartRect.height;
f.rectangle(x1, y1, x2 - x1, y2);
});
restoreAxis(c.axes.bottom, h);
};
history.push([Chart1.axes.bottom.minimum, Chart1.axes.bottom.maximum]);
Chart1.draw();
}
<script src="https://www.steema.com/files/public/teechart/html5/latest/src/teechart.js"></script>
<script src="https://www.steema.com/files/public/teechart/html5/latest/src/teechart-extras.js"></script>
<body onload="draw()">
<div class="x_content">
<br><canvas id="canvas" width="600" height="400">
This browser does not seem to support HTML5 Canvas.
</canvas>
<br/>
<canvas id="canvas2" width="520" height="50" style="margin-left : 70px;">
This browser does not seem to support HTML5 Canvas.
</canvas>
<br/>
<span id="data" />
</div>
</body>

Can't create text in easeljs

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.

Creating simple game but nothing showing up on the canvas

<html>
<head>
<title>Sean Coyne</title>
<link rel="stylesheet" type="text/css" href="home.css">
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<section>
<article>
<div id="logo"><img src="LogoComic.png" id="Logo"></div><br></br>
<div id="canvas">
<canvas id="c" style="border:5px solid orange" height="500" width="500"></canvas>
<p id="p1"></p>
<script>
var basket_x=100;
var basket_y=100;
var ball_x=100;
var ball_y=100;
var points=0;
//Background colour of canvas
var c = document.getElementById("c");
var ctx = c.getContext("2d");
ctx.fillStyle = "#0000";
ctx.fillRect(0,0,500,500);
//Here is the event listener
mycanv.addEventListener("mousemove",seenmotion,false);
function seenmotion(e) {
//This is the code for the mouse
//moving over the canvas.
var bounding_box=mycanv.getBoundingClientRect();
basket_x=(e.clientX-bounding_box.left) *
(mycanv.width/bounding_box.width);
basket_y=(e.clientY-bounding_box.top) *
(mycanv.height/bounding_box.height);
}
function start_game() {
setInterval(game_loop, 50);
}
function game_loop() {
// The code above is called every 50ms and is a
// frame-redraw-game-animation loop.
mycanv.width=mycanv.width;
// Below is the code that draw the objects
draw_basket(basket_x,basket_y);
draw_ball(ball_x,ball_y);
// Below is the code that updates the balls location
ball_x++;
if (ball_x>mycanv.width) {
ball_x=0;
}
//Here is the collision detection code
if (collision(basket_x, basket_y, ball_x, ball_y)) {
points -= 1;
}
//Here is the code for the point system
points+=1
// and let's stick it in the top right.
var integerpoints=Math.floor(points); // make it into an integer
ctx.font="bold 24px sans-serif #fff";
ctx.fillText(integerpoints, mycanv.width-50, 50);
}
function collision(basket_x, basket_y, ball_x, ball_y) {
if(basket_y + 85 < ball_y) {
return false;
}
if (basket_y > ball_y + 91) {
return false;
}
if (basket_x + 80 < ball_x) {
return false;
}
if (basket_x > ball_x + 80) {
return false;
}
return true;
}
// Code to stop the game when we're finished playing
function stop_game() {
}
//Code for the ball
function draw_ball(x,y) {
var c = document.getElementById("c");
var ctx = c.getContext("2d");
ctx.fillStyle = "#fff";
ctx.fillRect(0,0,20,20);
}
//Code for the basket
function draw_basket(x,y) {
var basket_img=new Image();
basket_img.src="basket.png";
ctx.drawImage(basket_img,x,y);
}
start_game()
</script>
</div>
</article>
</section>
You are never calling start_game() to start the program, thus the program just waits. Instead, at the end of your <script>, add start_game().
Just a tip: your line mycanv.width = mycanv.width is completely unnecessary, it is the equivalent of saying var x = 1; x = x;.

How to make my drawing put on the 1st plan of canvas?

This blue circle is spawning back there, when I need him spawning on the front. What can be wrong? Is it because the canvas background loads only onmouseover? or because it's random or because the grid itself isn't as big as canvas? I'm really confused.
<!doctype html>
<html>
<head>
<title>Ussi l6una</title>
<script>
var kohad=new Array();
var pikkus=1, d=6, kogus=300;
var ballx=0, step=100;
var bally=0, step=100;
var monsterx=(step*parseInt(5*Math.random())), step=100;
var monstery=(step*parseInt(5*Math.random()));
function toit(){
var c=document.getElementById("tahvel");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.fillStyle = 'darkblue';
ctx.arc(monsterx+10, monstery+10, 25, 0, 2 * Math.PI, false);
ctx.fill();
ctx.lineWidth = 0;
ctx.strokeStyle = '#000000';
}
function devouring(){
if(monsterx==ballx && bally==monstery){
monsterx=step*parseInt(5*Math.random());
monstery=step*parseInt(5*Math.random());
toit();
cnt++;
punktid();
}
}
function looKohad(){
for(var i=0; i<kogus; i++){
kohad[i]=new Array(pikkus*i, 1200);
}
}
function arvutaUusTagumine(eesmine, tagumine){
var kaugus=new Array();
kaugus[0]=eesmine[0]-tagumine[0];
kaugus[1]=eesmine[1]-tagumine[1];
var kogukaugus=Math.sqrt(kaugus[0]*kaugus[0]+kaugus[1]*kaugus[1]);
var nihe=kogukaugus-pikkus;
var dx=kaugus[0]*nihe/kogukaugus;
var dy=kaugus[1]*nihe/kogukaugus;
return new Array(tagumine[0]+dx, tagumine[1]+dy);
}
function arvutaUuedKohad(){
console.log(kohad);
for(var i=1; i<kogus; i++){
kohad[i]=arvutaUusTagumine(kohad[i-1], kohad[i]);
}
}
function joonistaKohad(g){
for(var i=0; i<kogus; i++){
joonistaKoht(g, kohad[i])
}
}
function joonistaKoht(g, koht){
g.beginPath();
g.arc(koht[0], koht[1], d, 0, 2*Math.PI, true);
g.stroke();
}
function hiirLiigub(e){
var t=document.getElementById("tahvel");
var g=t.getContext("2d");
var tahvlikoht=t.getBoundingClientRect();
kohad[0][0]=e.clientX-tahvlikoht.left;
kohad[0][1]=e.clientY-tahvlikoht.top;
arvutaUuedKohad();
g.strokeStyle="#CC9966";
g.fillStyle="#CC9966";
g.clearRect(0, 0, t.width, t.height);
joonistaKohad(g);
}
looKohad();
</script>
</head>
<body
onLoad="toit();">
<canvas id="tahvel" width="800" height="800"
style="background-color:white" onmousemove="hiirLiigub(event)" onmouseover="this.style.backgroundImage = 'url(./dirt.png)'"></canvas><br />
</body>
</html>
You simply forgot to call toit() after joonistaKohad(g); in the main draw loop.
Since you clear the canvas, you have to redraw everything afterwise.
Nice result by the way.
http://jsbin.com/UVoXOreV/1/

Categories

Resources