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

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/

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.

How to link P5.js setup and draw with html canvas?

I am sure this is a very simple thing to do, but I am stuck here.
Here is the situation:
I have an HTML page with a div and a canvas element(not sure if I need this)
Also I have two javascript files using p5.js with setup and draw funtions where I draw my content on a canvas I create with createCanvas.
The other js file contains an object.
The problem is - I can get the animation to show on the HTML page, but not inside the div and/or canvas.
Image for a clearer picture:
HTML and JS comunication
HTML:
<html>
<head>
<meta charset="utf-8">
<title>Fractals</title>
<script language="javascript" type="text/javascript" src="libs/p5.js"></script>
<script language="javascript" src="libs/p5.dom.js"></script>
<script language="javascript" type="text/javascript" src="sketch.js"></script>
<script language="javascript" type="text/javascript" src="branch.js"></script>
<style>
body {
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div>
<canvas id="fractal" height="197" width="333" style=" width:333;height:197;"></canvas>
</div>
</body>
</html>
JS sketch:
var tree = [];
var x;
var y;
function setup() {
createCanvas(333,197);
var a = createVector(width / 2, height);
var b = createVector(width / 2, height - 50);
var root = new Branch(a, b);
tree[0] = root;
for (var t = 0; t < 5; t++) {
for (var i = tree.length-1; i >= 0; i--) {
if (!tree[i].finished){
tree.push(tree[i].branchA());
tree.push(tree[i].branchB());
tree.push(tree[i].branchC());
}
tree[i].finished = true;
}
}
}
function draw() {
background(51);
x = mouseX;
y = mouseY;
for (var i = 0; i < tree.length; i++) {
tree[i].show();
tree[i].wind(x, y, tree[i].end.x, tree[i].end.y);
}
}
JS branch object:
function Branch(begin, end) {
this.begin = begin;
this.end = end;
this.finished = false;
this.origx = this.end.x;
this.origy = this.end.y;
this.show = function() {
stroke(255);
line(this.begin.x, this.begin.y, this.end.x, this.end.y);
}
this.branchA = function() {
var dir = p5.Vector.sub(this.end, this.begin);
dir.rotate(19.2);
dir.mult(0.67);
var newEnd = p5.Vector.add(this.end, dir);
var v = new Branch(this.end, newEnd);
return v;
}
this.branchB = function() {
var dir = p5.Vector.sub(this.end, this.begin);
dir.rotate(0);
dir.mult(0.67);
var newEnd = p5.Vector.add(this.end, dir);
var v = new Branch(this.end, newEnd);
return v;
}
this.branchC = function() {
var dir = p5.Vector.sub(this.end, this.begin);
dir.rotate(-19.2);
dir.mult(0.67);
var newEnd = p5.Vector.add(this.end, dir);
var v = new Branch(this.end, newEnd);
return v;
}
this.wind = function(mox,moy,treex,treey) {
var d = dist(mox,moy,treex,treey);
if (d < 20) {
this.end.x += random(-0.3, 0.3);
this.end.y += random(-0.3, 0.3);
}else{
this.end.x = this.origx;
this.end.y = this.origy;
}
}
}
P5 libraries : https://p5js.org/download/
From the docs:
https://github.com/processing/p5.js/wiki/Positioning-your-canvas
// sketch.js
function setup() {
var canvas = createCanvas(100, 100);
// Move the canvas so it's inside our <div id="sketch-holder">.
canvas.parent('sketch-holder');
background(255, 0, 200);
}
Create one instance of canvas with P5, then assigns its parent by dom id.

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;.

cant draw images to canvas in js

Ok, so me and my friends are trying to make a game with html and js. I'm the one that has to build the foundation for the program to display the blocks used on the map. For some reason though, it doesn't want to draw my images on the canvas at all. I need to display a 24x32 array of 32x32 pixel blocks whose images I need to be able to change. I've looked online, and everywhere it says to use the function drawImage() but my program doesn't see that that belongs to the canvas under the 2d context. Here is my code:
index.html:
<html lang="en">
<head>
</head>
<body>
<div class="canvas">
<canvas id="canvas" height="768" width="1024" style="border:1px solid black">
Your browser does not support canvas element.
</canvas>
<script type="text/javascript" src="Main.js"></script>
<script type="text/javascript" src="World Loader.js"></script>
</div>
</body>
</html>
Main.js:
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.font = "20px Arial";
var FPS = 60;
var Mode = 0;
function displayTick(){
Map.DisplayChunk(0,0);
}
function gameTick(){
}
Chunk.LoadNew();
window.setInterval(displayTick, 1000 / FPS);
window.setInterval(gameTick, 600);
and World_Loader.js:
var Block={
WalkThrough:true,
SeeThrough:true,
Interactable:false,
Occupied:false,
Sprite:Image,
Type:"",
X:0,
Y:0
};
var Chunk={
matrix:Block[32][24],
background:Image,
display:function(xindex, yindex){
ctx.drawImage(Background,0,0);
x=xindex;
y=yindex;
for(y=0; y<24; Y++){
for(x=0; x<32; x++){
ctx.drawImage(matrix[X][Y].sprite,X*32,Y*32);
};
};
},
loadNew:function(){
for(Y=0; Y<24; Y++){
for(X=0; X<32; X++){
block=new Block;
block.Sprite.src="test.png";
this.matrix[X][Y]=block;
};
};
}
};
var World={
matrix:Chunk[5][5],
indexX:0,
indexY:0
};
I'm still new to js and trying to teach myself so there's probably tons of errors and stuff. But can anyone see how it doesn't want to draw on the canvas?
There is some problem with your script(sintax errors, scope trouble and so on), you should start with something more simple, I suggest you to start to read this online book.
Anyway below you can see a simple script to fill and display a little grid of images on a canvas.
var Map = (function () {
var options = arguments[0] || {};
var _grid = [];
var _rNum = options.rowuUm || 10;
var _cNum = options.colNum || 10;
var _block = function (x, y) {
this.img = document.getElementById('on');
this.X = x;
this.Y = y;
};
return {
init: function () {
for (var i = 0; i < _rNum; i++) {
_grid[i] = [];
for (var j = 0; j < _cNum; j++) {
_grid[i][j] = new _block(i, j);
}
}
},
paint: function (canvasId) {
var cnv = document.getElementById(canvasId);
var ctx = cnv.getContext('2d');
var img = new Image();
img.src = 'on.jpg';
img.onload = function () {
for (var i = 0; i < _rNum; i++) {
for (var j = 0; j < _cNum; j++) {
ctx.drawImage(img, i * 32, j * 32);
}
}
};
},
}
})();
Map.init();
Map.paint('canvas');

Calling and killing a parent function with onmouseover and onmouseout events

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/

Categories

Resources