How to make objects disappear when poining mouse over them in javascript? - javascript

So I have this game where a worm eats his food, food randomly spawns on load but I want it to disappear onmouseover and spawn again in another spot but I have no idea what to do :c Didn't find any info on the internet either, tho not quitet sure what to search for.
p.s. made this question again because last time people hated it because they thought that I don't have anything done. Thanx
<!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(8*Math.random())), step=100;
var monstery=(step*parseInt(8*Math.random()));
function toit(){
var c=document.getElementById("tahvel");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.fillStyle = 'darkblue';
ctx.arc(monsterx+30, monstery+30, 25, 0, 2 * Math.PI, false);
ctx.fill();
ctx.lineWidth = 0;
ctx.strokeStyle = '#000000';
}
function devouring(){
if(toitx==mousex && toity==mousey){
toitx=step*parseInt(5*Math.random());
toity=step*parseInt(5*Math.random());
toit();
}
}
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);
toit();
}
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>

Related

drawing more on the canvas without having to create more script tags

I've been attempting to create a ecology simulation and so far its been going good. The code below does work I'm just wondering if theres an easier way to draw more items on the canvas with code instead of manually doing it. The way I'm doing it makes me consider the lag because I will be adding a lot to the code (e.g. move, detected, reproduce, chase, run, etc). Thank you for seeing this
//This tag will regulate the spawning of new sheep/wolves
var totalWolves = 0;
var totalSheep = 0;
var canavs = document.getElementById("canvas");
var body = document.getElementById("body");
//styler
body.style.overflow = "hidden";
body.style.margin = "0px";
canvas.style.backgroundColor = "black";
function spawnWolves(){
totalWolves++;
var name = "wolf" + totalWolves;
var scrpt = document.createElement("SCRIPT");
document.body.appendChild(scrpt);
scrpt.setAttribute("id", name);
var script = document.getElementById(name);
script.innerHTML = "var rand3 = Math.floor(Math.random() * 100) + 1; var rand4 = Math.floor(Math.random() * 100) + 1; var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.fillStyle = 'red'; context.fillRect(rand3, rand4, 10, 10); context.fill();";
}
spawnWolves();
spawnWolves();
spawnWolves();
<!DOCTYPE html>
<html>
<head>
<title>AI spawn test</title>
</head>
<body id="body">
<canvas id="canvas" width="1366px" height="768px"/>
<script>
</script>
</body>
</html>
Your solution seems very complicated ...
Please, take a look at the following code.
<!DOCTYPE html>
<html>
<title>AI spawn test</title>
<canvas id="canvas" width="110" height="110"></canvas>
<script>
var ctx = canvas.getContext("2d");
var drawRect=function(rects){
for (var i=1; i<=rects; i++){
var rand3=Math.floor(Math.random() * 100) + 1;
var rand4=Math.floor(Math.random() * 100) + 1;
ctx.fillStyle='red';
ctx.fillRect(rand3, rand4, 10, 10)
}
}
drawRect(20);
</script>
This type of 'replication' is done by using loop. There are several loop types, but their explanation is too broad. You can browse the net.
I gave you 2 examples below - with for loop and with while loop.
//This tag will regulate the spawning of new sheep/wolves
var totalWolves = 0;
var totalSheep = 0;
var canavs = document.getElementById("canvas");
var body = document.getElementById("body");
//styler
body.style.overflow = "hidden";
body.style.margin = "0px";
canvas.style.backgroundColor = "black";
function spawnWolves(){
totalWolves++;
var name = "wolf" + totalWolves;
var scrpt = document.createElement("SCRIPT");
document.body.appendChild(scrpt);
scrpt.setAttribute("id", name);
var script = document.getElementById(name);
script.innerHTML = "var rand3 = Math.floor(Math.random() * 100) + 1; var rand4 = Math.floor(Math.random() * 100) + 1; var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.fillStyle = 'red'; context.fillRect(rand3, rand4, 10, 10); context.fill();";
}
for(var i=0; i<12; i++)
{
spawnWolves();
}
var maxWolves=9;
while(totalWolves < maxWolves)
{
spawnWolves();
}
<!DOCTYPE html>
<html>
<head>
<title>AI spawn test</title>
</head>
<body id="body">
<canvas id="canvas" width="1366px" height="768px"/>
<script>
</script>
</body>
</html>
The first loop will run until its internal counter i goes from 0 to 12 and will call the function exactly 12 times.
The second loop will run as long as the condition totalWolves < maxWolves is true. totalWolves is your counter you increase in your function and maxWolves is the limit when you want the loop to stop.
Because these 2 examples are added here one after another the second wont work. After the first one executes you will already have 12 wolves and the second loop will not enter because 12 < 9 is false.

javascript drawing one more polygon

I want to draw a lot of polygons on a canvas by mouse handlers with pure Javascript language. My project is here.
In my project:
I want to finish draw and create a polygon when I do double click. (I can).
After start a drawing by one click event for make new polygon. (I can't).
When I start new draw adding new point to polygon before maked.
Thank you.
My html file is here:
<html>
<head>
<title>Orhan ALTIN</title>
<meta charset="utf-8">
<style>
canvas{
border: 5px solid;
border-color: rgb(255,173,50);
}
</style>
</head>
<body>
<canvas id="tuval" width="500" height="500"></canvas>
<script>
var tuval = document.getElementById("tuval");
var kaynak = tuval.getContext("2d");
var simdiX=[];
var simdiY=[];
var sonraX=[];
var sonraY=[];
var cizgiler=[];
var cizgi={
x1:0,
y1:0
};
var bas=0;
var fare={
xx:0,
yy:0
};
var cevre=tuval.getBoundingClientRect();
var cizimyap=false;
var yeni=0;
tuval.addEventListener("click",function temizle(olay){
cizimyap=true;
fare={
xx:olay.clientX-cevre.left,
yy:olay.clientY-cevre.top
};
cizgi.x1=fare.xx;
cizgi.y1=fare.yy;
bas=bas+1;
kaynak.moveTo(fare.xx,fare.yy);
bas++;
if(bas>1){
cizgiler.push({
xx1:cizgi.x1,
yy1:cizgi.y1,
xx2:cizgi.x2,
yy2:cizgi.y2
});
}
tuval.addEventListener("mousemove", function oynat(olay){
if (cizimyap) {
kaynak.clearRect(0,0,tuval.width,tuval.height);
kaynak.beginPath();
for (var i = 0, max = cizgiler.length; i < max; i++) {
var dizi=cizgiler[i];
kaynak.moveTo(dizi.xx2,dizi.yy2);
kaynak.lineTo(dizi.xx1,dizi.yy1);
kaynak.stroke();
simdiX.push(dizi.xx1);
simdiY.push(dizi.yy1);
}
kaynak.moveTo(fare.xx,fare.yy);
kaynak.lineTo(olay.clientX-cevre.left,olay.clientY-cevre.top);
kaynak.stroke();
}
});
tuval.addEventListener("dblclick", function(){
cizimyap=false;
poligonYap(olay);
});
});
function poligonYap(olay){
simdiX.splice(simdiX.length-1,1,simdiX[0]);
simdiY.splice(simdiY.length-1,1,simdiY[0]);
kaynak.clearRect(0,0,tuval.width,tuval.height);
for (var i = 0, max = cizgiler.length; i < max; i++) {
//var dizi=cizgiler[i];
kaynak.strokeStyle="green";
kaynak.lineWidth="1";
kaynak.lineCap="round";
sonraX[i]=simdiX[i];
sonraY[i]=simdiY[i];
kaynak.lineTo(sonraX[i],sonraY[i]);
kaynak.stroke();
}
for (var i = 0, max = cizgiler.length-1; i < max; i++) {
kaynak.fillStyle="blue";
kaynak.fillRect(cizgiler[i].xx1-5/2,cizgiler[i].yy1-5/2,5,5);
kaynak.font="12px Tahoma";
kaynak.fillStyle="red";
kaynak.fillText(i+1,cizgiler[i].xx1,cizgiler[i].yy1-5);
}
}
</script>
</body>

How to write a loop so that I will draw to user canvas?

I have a canvas element. I have a few troubles, how to draw to user canvas in "realtime",.. So, that my drawing is not already there when they open the site, but rather to draw to the canvas like somebody is actually drawing... So looping through the coordinates.
That's what I tried so far but it's BAAD! It's drawing slowly and it takes a lot of CPU.
// Pencil Points
var ppts = [];
/* Drawing on Paint App */
tmp_ctx.lineWidth = 4;
tmp_ctx.lineJoin = 'round';
tmp_ctx.lineCap = 'round';
tmp_ctx.strokeStyle = '#4684F6';
tmp_ctx.fillStyle = '#4684F6';
// Tmp canvas is always cleared up before drawing.
tmp_ctx.clearRect(0, 0, tmp_canvas.width, tmp_canvas.height);
tmp_ctx.beginPath();
var timer = 0;
$.timer(500, function() {
ppts.push({x: 10*timer, y: 5*timer});
timer++;
})
$.timer(10, function() {
if (timer > 250) {
timer = 0;
clearTempCanvas();
} else {
for (var i = 1; i < ppts.length - 2; i++) {
var c = (ppts[i].x + ppts[i + 1].x) / 2;
var d = (ppts[i].y + ppts[i + 1].y) / 2;
tmp_ctx.quadraticCurveTo(ppts[i].x, ppts[i].y, c, d);
}
console.log(i);
tmp_ctx.stroke();
}
})
function clearTempCanvas() {
// Writing down to real canvas now
ctx.drawImage(tmp_canvas, 0, 0);
// Clearing tmp canvas
tmp_ctx.clearRect(0, 0, tmp_canvas.width, tmp_canvas.height);
// Emptying up Pencil Points
ppts = [];
}
Here's an example for you to learn from: http://jsfiddle.net/m1erickson/j4HWS/
It works like this:
define some points to animate along and put those points in an array points.push({x:25,y:50})
use requestAnimationFrame to create an animation loop
break each line segment into 100 sub-segments and animate along those sub-segments
Example code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.lineWidth=2;
ctx.strokeStyle="blue";
var points=[];
points.push({x:125,y:125});
points.push({x:250,y:200});
points.push({x:125,y:200});
points.push({x:125,y:125});
var pointIndex=1;
var linePct=0;
var continueAnimating=true;
var img=new Image();img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/pen.png";
function start(){
animate();
}
function draw(pointIndex,linePct){
// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
// draw fully completed lines
ctx.beginPath();
ctx.moveTo(points[0].x,points[0].y);
for(var i=1;i<pointIndex;i++){
ctx.lineTo(points[i].x,points[i].y);
}
// draw current line-in-process
var pos=getLineXYatPercent(points[pointIndex-1],points[pointIndex],linePct/100);
ctx.lineTo(pos.x,pos.y);
ctx.stroke();
// draw the pen
ctx.drawImage(img,pos.x-93,pos.y-92);
}
function animate() {
if(!continueAnimating){return;}
requestAnimationFrame(animate);
// Drawing code goes here
draw(pointIndex,linePct);
if(++linePct>100){
linePct=1;
if(++pointIndex>points.length-1){
continueAnimating=false;
}
}
}
function getLineXYatPercent(startPt,endPt,percent) {
var dx = endPt.x-startPt.x;
var dy = endPt.y-startPt.y;
var X = startPt.x + dx*percent;
var Y = startPt.y + dy*percent;
return( {x:X,y:Y} );
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=350 height=350></canvas>
</body>
</html>

html5 canvas collision detection with multiple blocks

I've been trying to create a game with falling blocks that will stack on top of each other. The blocks will fall into one of 6 columns and need to stop falling down the screen when they collide with the top block on that column. I've been trying to get the y-coordinate of the top block, but that causes a problem because its still getting the newest created block and not the last finished block. Any help would be greatly appreciated!
var FPS = 60;
setInterval(function() {
//update();
draw();
}, 1000/FPS);
var y = 30;
//draw the screen
function draw() {
if(+new Date() > lastTime + minWait){
var column = Math.floor(Math.random()*6)
lastTime = +new Date();
blocks.push(new Block(5 + column*40, 30,40,40, 5, "red","black"));
}
context.clearRect(0,0,canvas.width, canvas.height);
blocks.forEach(function(e){
e.update();
e.render();
});
};
var blocks = [];
var lastTime = +new Date();
var minWait = 1000;
var topBlock = 310;
function columnTop(column){
for(var i=0; i < blocks.length; i++){
if(blocks[i].x === (5 + 40*columnTop)){
if(blocks[i].y < topBlock){
topBlock = blocks[i].y
}
}
}
}
//block functions
Block.prototype.update = function(){
var topCol1 = columnTop(1);
var topCol2 = columnTop(2);
var topCol3 = columnTop(3);
var topCol4 = columnTop(4);
var topCol5 = columnTop(5);
var topCol6 = columnTop(6);
if(this.y < 310){
this.y+= this.dy
}else{
this.dy = 0;
}
};
Block.prototype.render = function(){
Block(this.x, this.y, this.w, this.h, this.r, this.fillstyle, this.strokestyle);
};
Maintain a maximum-Y value for each column.
maximum-Y is the y-position of the last stacked block.
Whenever a block exceeds the maximum-Y, force that block to sit atop the maximum-Y.
Then reduce maximum-Y by that blocks height.
if( block.y + block.height > maxY ){
block.y = maxY - block.height;
maxY = block.y;
}
Here's code and a Demo: http://jsfiddle.net/m1erickson/FMv2q/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
function Blocks(floor,colCount){
this.blocks=[];
this.floor=floor;
this.cols=[];
this.continueRAF=true;
for(var i=0;i<colCount;i++){
this.cols.push({maxY:floor,needsNewBlock:true});
}
}
function animate(){
if(blocks.continueRAF){ requestAnimationFrame(animate); }
for(var i=0;i<blocks.cols.length;i++){
if(blocks.cols[i].needsNewBlock){
blocks.cols[i].needsNewBlock=false;
blocks.blocks.push(new Block(i));
}
}
ctx.clearRect(0,0,canvas.width,canvas.height);
var fallingCount=0;
for(var i=0;i<blocks.blocks.length;i++){
var block=blocks.blocks[i];
fallingCount+=block.fall();
ctx.fillStyle=block.fill;
ctx.fillRect(block.x,block.y,block.w,block.h);
}
if(fallingCount==0 && blocks.continueRAF){
blocks.continueRAF=false;
alert("All done after "+blocks.blocks.length+" blocks fell.");
}
}
function Block(column){
this.column=column;
this.x=this.column*50;
this.w=parseInt(Math.random()*20+15);
this.h=parseInt(Math.random()*15+5);
this.y=-this.h;
this.vy=parseInt(Math.random()*3+4);
this.fill=randomColor();;
this.isFalling=true;
}
Block.prototype.fall=function(){
if(!this.isFalling){return(0);}
var col=blocks.cols[this.column];
if(this.y+this.h+this.vy>col.maxY){
this.isFalling=false;
this.y=col.maxY-this.h;
col.maxY=this.y;
if(col.maxY>35){
col.needsNewBlock=true;
}
}else{
this.y+=this.vy;
}
return(1);
}
var blocks=new Blocks(350,6);
animate();
function randomColor(){
return('#'+Math.floor(Math.random()*16777215).toString(16));
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=350 height=350></canvas>
</body>
</html>

How to make objects disappear when pointng mouse over them in javascript?

So I have this game where a worm eats his food, food randomly spawns on load but I want it to disappear onmouseover and spawn again in another spot but I have no idea what to do :c Didn't find any info on the internet either, tho not quitet sure what to search for.
p.s. made this question again because last time people hated it because they thought that I don't have anything done. Thanx
<!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(8*Math.random())), step=100;
var monstery=(step*parseInt(8*Math.random()));
function toit(){
var c=document.getElementById("tahvel");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.fillStyle = 'darkblue';
ctx.arc(monsterx+30, monstery+30, 25, 0, 2 * Math.PI, false);
ctx.fill();
ctx.lineWidth = 0;
ctx.strokeStyle = '#000000';
}
function devouring(){
if(toitx==mousex && toity==mousey){
toitx=step*parseInt(5*Math.random());
toity=step*parseInt(5*Math.random());
toit();
}
}
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);
toit();
}
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>

Categories