Ok, so i'm very new to javascript, and i'm just making my first non-tutorial game, just a simple bullethell thing. I made it so that bullets randomly fly from the walls, but it only does that once. I want it to fire the bullets from a random place, wait about 1 second, then fire 4 more bullets from other random places. THANK YOU IN ADVANCE!
Heres the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Square</title>
<style>
* { padding: 0; margin: 0; }
canvas { background: #eee; display: block; margin: 0 auto; }
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<fom name="Show">
<input type="text" name="MouseX" value="0" size="4"> X<br>
<input type="text" name="MouseY" value="0" size="4"> Y<br>
</form>
<script language="JavaScript1.2">
var canvas=document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x=canvas.width/2;
var y=canvas.height-30;
var playerHeight = 20;
var playerWidth = 20;
var enemyHeight = 10;
var enemyWidth = 10;
var IE = document.all?true:false
var randRight = Math.random()*320;
var randLeft = Math.random()*320;
var randTop = Math.random()*320;
var randBottom = Math.random()*320;
var enemyXPosRight = 480;
var enemyXPosLeft = 0;
var enemyYPosTop = 0;
var enemyYPosBottom = 320;
var rep = true;
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;
var tempX = 0
var tempY = 0
// Main function to retrieve mouse x-y pos.s
function getMouseXY(e) {
if (IE) {
tempX = event.clientX + document.body.scrollLeft
tempY = event.clientY + document.body.scrollTop
} else {
tempX = e.pageX
tempY = e.pageY
}
if (tempX < 0){tempX = 0}
if (tempY < 0){tempY = 0}
document.Show.MouseX.value = tempX
document.Show.MouseY.value = tempY
return true
}
function drawPlayer() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.rect(tempX-500, tempY-20, playerWidth, playerHeight);
ctx.fill();
ctx.closePath();
if (tempX < 500) {
tempX = 500;
}
if (tempX > 960) {
tempX = 960;
}
if (tempY < 38) {
tempY = 38;
}
if (tempY > 340) {
tempY = 340;
}
}
function drawEnemyRight() {
ctx.beginPath();
ctx.rect(enemyXPosRight-=3, randRight, enemyWidth, enemyHeight);
ctx.fill();
ctx.closePath();
}
function drawEnemyLeft() {
ctx.beginPath();
ctx.rect(enemyXPosLeft+=3, randLeft, enemyWidth, enemyHeight);
ctx.fill();
ctx.closePath();
}
function drawEnemyTop() {
ctx.beginPath();
ctx.rect(randTop, enemyYPosTop+=3, enemyWidth, enemyHeight);
ctx.fill();
ctx.closePath();
}
function drawEnemyBottom() {
ctx.beginPath();
ctx.rect(randBottom, enemyYPosBottom-=3, enemyWidth, enemyHeight);
ctx.fill();
ctx.closePath();
}
function draw() {
drawPlayer();
drawEnemyBottom();
drawEnemyRight();
drawEnemyLeft();
drawEnemyTop();
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
Related
I am trying to draw a straight line on canvas using mouse events.I am new to java script. Can anybody help or refer something from where i can get help?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin: auto;
left: 0;
right: 0;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var bounds = null;
var ctx = null;
var hasLoaded = false;
var startX = 0;
var startY = 0;
var mouseX = 0;
var mouseY = 0;
var isDrawing = false;
var existingLines = [];
function draw() {
ctx.fillStyle = "#333333";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
for (var i = 0; i < existingLines.length; ++i) {
var line = existingLines[i];
ctx.moveTo(line.startX,line.startY);
ctx.lineTo(line.endX,line.endY);
}
ctx.stroke();
if (isDrawing) {
ctx.strokeStyle = "darkred";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(startX,startY);
ctx.lineTo(mouseX,mouseY);
ctx.stroke();
}
}
function onmousedown(e) {
if (hasLoaded && e.button === 0) {
if (!isDrawing) {
startX = e.clientX - bounds.left;
startY = e.clientY - bounds.top;
isDrawing = true;
}
draw();
}
}
function onmouseup(e) {
if (hasLoaded && e.button === 0) {
if (isDrawing) {
existingLines.push({
startX: startX,
startY: startY,
endX: mouseX,
endY: mouseY
});
isDrawing = false;
}
draw();
}
}
function onmousemove(e) {
if (hasLoaded) {
mouseX = e.clientX - bounds.left;
mouseY = e.clientY - bounds.top;
if (isDrawing) {
draw();
}
}
}
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.onmousedown = onmousedown;
canvas.onmouseup = onmouseup;
canvas.onmousemove = onmousemove;
bounds = canvas.getBoundingClientRect();
ctx = canvas.getContext("2d");
hasLoaded = true;
draw();
}
</script>
</body>
</html>
How can I create an 'infinite' canvas with text boxes dotted around? Like this one at the Desmos site.
I have not managed to implement it myself.
The simplest approach to a pan-able canvas is to draw everything relative to an offset, in this example I have called this panX & panY. Imagine it as a coordinate you use to move the viewport (the area of the infinite board that is currently visible in the canvas).
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
var imageWidth = 180;
var imageHeight = 160;
var canvas = null;
var ctx = null;
var bounds = null;
var selectedBox = null;
var panX = 0;
var panY = 0;
var mouseX = 0;
var mouseY = 0;
var oldMouseX = 0;
var oldMouseY = 0;
var mouseHeld = false;
var boxArray = [];
function DraggableBox(x,y,width,height,text) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.text = text;
this.isSelected = false;
}
DraggableBox.prototype.isCollidingWidthPoint = function(x,y) {
return (x > this.x && x < this.x + this.width)
&& (y > this.y && y < this.y + this.height);
}
DraggableBox.prototype.drag = function(newX,newY) {
this.x = newX - this.width * 0.5;
this.y = newY - this.height * 0.5;
}
DraggableBox.prototype.draw = function() {
if (this.isSelected) {
ctx.fillStyle = "darkcyan";
ctx.fillRect(
this.x - panX,
this.y - panY,
this.width,
this.height
);
ctx.fillStyle = "black";
} else {
ctx.fillRect(
this.x - panX,
this.y - panY,
this.width,
this.height
);
}
ctx.fillStyle = "white";
ctx.fillText(
this.text,
this.x + this.width * 0.5 - panX,
this.y + this.height * 0.5 - panY,
this.width
);
ctx.fillStyle = "black";
}
window.onmousedown = function(e) {
mouseHeld = true;
if (!selectedBox) {
for (var i = boxArray.length - 1; i > -1; --i) {
if (boxArray[i].isCollidingWidthPoint(mouseX + panX,mouseY + panY)) {
selectedBox = boxArray[i];
selectedBox.isSelected = true;
requestAnimationFrame(draw);
return;
}
}
}
}
window.onmousemove = function(e) {
mouseX = e.clientX - bounds.left;
mouseY = e.clientY - bounds.top;
if (mouseHeld) {
if (!selectedBox) {
panX += oldMouseX - mouseX;
panY += oldMouseY - mouseY;
} else {
selectedBox.x = mouseX - selectedBox.width * 0.5 + panX;
selectedBox.y = mouseY - selectedBox.height * 0.5 + panY;
}
}
oldMouseX = mouseX;
oldMouseY = mouseY;
requestAnimationFrame(draw);
}
window.onmouseup = function(e) {
mouseHeld = false;
if (selectedBox) {
selectedBox.isSelected = false;
selectedBox = null;
requestAnimationFrame(draw);
}
}
function draw() {
ctx.fillStyle = "gray";
ctx.fillRect(0,0,imageWidth,imageHeight);
var box = null;
var xMin = 0;
var xMax = 0;
var yMin = 0;
var yMax = 0;
ctx.fillStyle = "black";
for (var i = 0; i < boxArray.length; ++i) {
box = boxArray[i];
xMin = box.x - panX;
xMax = box.x + box.width - panX;
yMin = box.y - panY;
yMax = box.y + box.height - panY;
if (xMax > 0 && xMin < imageWidth && yMax > 0 && yMin < imageHeight) {
box.draw();
}
}
}
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = imageWidth;
canvas.height = imageHeight;
bounds = canvas.getBoundingClientRect();
ctx = canvas.getContext("2d");
ctx.textAlign = "center";
ctx.font = "15px Arial"
boxArray.push(new DraggableBox(Math.random() * 320,Math.random() * 240,100,25,"This is a draggable text box"));
boxArray.push(new DraggableBox(Math.random() * 320,Math.random() * 240,100,50,"Another text box"));
boxArray.push(new DraggableBox(Math.random() * 320,Math.random() * 240,100,50,"Text in a box"));
boxArray.push(new DraggableBox(Math.random() * 320,Math.random() * 240,100,50,"I find this box quite texing"));
boxArray.push(new DraggableBox(Math.random() * 320,Math.random() * 240,150,50,"You weren't supposed to find this box"));
requestAnimationFrame(draw);
}
window.onunload = function() {
canvas = null;
ctx = null;
bounds = null;
selectedBox = null;
boxArray = null;
}
</script>
</body>
</html>
how can I optimize this code to render sine wave without little blurring that happens when canvas is re-drawen
var canvas = document.getElementById("sinewave");
var points = {};
var counter = 0;
var intensity = 0;
function f(x, intensity) {
return intensity * Math.sin(0.25 * x) + 100;
}
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
var x = 0,
y = f(0,0);
var timeout = setInterval(function() {
if(counter < 400) {
ctx.beginPath();
ctx.moveTo(x, y);
x += 1;
y = f(x, intensity);
points[x] = y;
ctx.lineTo(x, y);
ctx.stroke();
if (x > 1000) {
clearInterval(timeout);
}
} else {
ctx.clearRect(0, 0, 400, 200);
ctx.beginPath();
points[x] = y;
x += 1;
y = f(x, intensity);
for(var i = 0; i < 400; i++) {
ctx.lineTo(i, points[i + counter - 400]);
}
ctx.stroke();
}
counter++;
}, 5);
}
Some thoughts:
Since x==0 & intensity==0 the first 400 plots form a straight line(?).
Your setInterval time is too short (5ms). The screen refreshes only about every 17ms so you are accumulating interval calls that the browser will futilely try to fill. (You're getting clogged up!).
Use the new(ish) requestAnimationFrame instead of setInterval because requestAnimationFrame is better integrated with the display hardware.
Here's example refactored code and Demo: http://jsfiddle.net/m1erickson/MZ7Ap/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: black; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
var points = {};
var counter = 0;
var intensity = 2;
var x = 0;
var y = fz(0,0);
animate();
function fz(x, intensity) {
return intensity * Math.sin(0.25 * x) + 100;
}
function animate(time){
requestAnimationFrame(animate);
draw(counter);
counter++;
}
function draw(counter){
if(counter < 400) {
ctx.beginPath();
ctx.moveTo(x, y);
x += 1;
y = fz(x, intensity);
points[x] = y;
ctx.lineTo(x, y);
ctx.stroke();
if (x > 1000) {
clearInterval(timeout);
}
} else {
ctx.clearRect(0, 0, 400, 200);
ctx.beginPath();
points[x] = y;
x += 1;
y = fz(x, intensity);
for(var i = 0; i < 400; i++) {
ctx.lineTo(i, points[i + counter - 400]);
}
ctx.stroke();
}
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=900 height=300></canvas>
</body>
</html>
the code
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<style>
body {
background-color:#E4E0FF;
}
#canvas {
border:10px solid red;
background-color:white;
}
#canvas1 {
border:10px solid red;
background-color:white;
}
#canvas2 {
border:10px solid red;
background-color:white;
}
</style>
</head>
<body>
<h1>My canvas Art Gallery</h1>
<canvas id="canvas" width="400" height="300">
</canvas>
<canvas id="canvas1" width="400" height="300">
</canvas>
<canvas id="canvas2" width="400" height="300">
</canvas>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script type="text/javascript">
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
var changeRadius;
var changeWidth;
var isDown = false;
var startX;
var startY;
var toggle=0;
var x=150;
var y=100;
var w=100;
var h=100;
var r=60;
var wasInside=false;
ctx.fillStyle = "#000000";
ctx.fillRect(x, y, w, h);
function changeColor() {
if (toggle == 0) {
ctx.fillStyle = "#04B45F";
toggle = 1;
} else if (toggle ==1){
ctx.fillStyle = "#04B45F";
toggle = 2;
}else if (toggle == 2){
ctx.fillStyle = "#0000FF";
toggle = 3;
}else if (toggle == 3){
ctx.fillStyle == "#190707";
toggle = 4;
}else if (toggle == 4){
ctx.fillStyle = "#210B61";
toggle = 5;
}else if (toggle == 5){
ctx.fillStyle = "#FA58AC";
toggle = 6;
}else if (toggle ==6){
ctx.fillStyle = "#FFFF00";
toggle = 7;
}else{
ctx.fillStyle = "#F5A9D0";
toggle = 0;
}
ctx.fillRect(x, y, w, h);
}
(function () {
var c1 = document.getElementById("canvas1");
var ctx = c1.getContext("2d");
var $canvas = $("#canvas1");
var toggle = 0;
var x = 150;
var y = 100;
var w = 100;
var h = 100;
var r = 60;
var wasInside = false;
ctx.beginPath();
ctx.arc(200, 150, r, 0, 2 * Math.PI);
ctx.stroke();
changeRadius = function changeRadius() {
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0, 0, 400, 300);
r = Math.floor((Math.random() * 80) + 20);
ctx.beginPath();
ctx.arc(200, 150, r, 0, 2 * Math.PI);
ctx.stroke();
}
})();
(function () {
var c = document.getElementById("canvas2");
var ctx = c.getContext("2d");
var $canvas = $("#canvas2");
var toggle = 0;
var x = 150;
var y = 100;
var w = 100;
var h = 100;
var width = 2;
var wasInside = false;
ctx.lineWidth = width;
ctx.moveTo(150,100);
ctx.lineTo(250,200);
ctx.stroke();
changeWidth = function changeWidth() {
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0,0, 400, 300);
width = Math.floor((Math.random()*50)+1);
ctx.lineWidth=width;
ctx.stroke();
}
})();
function handleMouseMove(e, canv) {
console.log(canv);
var mx = parseInt(e.clientX - offsetX);
var my = parseInt(e.clientY - offsetY);
var isInsideNow = (mx > x && mx < x + w && my > y && my <= y + h);
if (isInsideNow && !wasInside) {
switch(canv.id){
case 'canvas':
changeColor();
break;
case 'canvas1' :
changeRadius();
break;
case 'canvas2':
changeWidth();
break;
}
wasInside = true;
} else if (!isInsideNow && wasInside) {
wasInside = false;
}
}
$("#canvas, #canvas1, #canvas2").mousemove(function (e) {
handleMouseMove(e,this);
});
</script>
</body>
</html>
Aim is to change the color in first, circle size in second and width of line in third canvas.
So, the problem is the location defined by x, y, w and h is in the first canvas and I can't get the any reaction from 2nd and 3rd canvas by the mouse. Here's the fiddle
http://jsfiddle.net/x5xH5/23/
how can I solve this??
Here I could get it working using .mouseenter and removing those many isInsides and others, though I am not sure if it satisfies your requirements:
DEMO
What I changed:
// Just the last few lines
function handleMouseMove(e, canv) {
console.log(canv);
switch(canv.id){
case 'canvas':
changeColor();
break;
case 'canvas1' :
changeRadius();
break;
case 'canvas2':
changeWidth();
break;
}
}
$("#canvas, #canvas1, #canvas2").mouseenter(function (e) {
handleMouseMove(e, this);
});
I am developing simple game with HTML5 Canvas. I used sprite image for animate, when I change position to absolute its not working and also touchevents are not working on canvas object, if change position to absolute then touchevents works fine but sprite stuff not works.
What might be the problem. Here is my JavaScript code.
Here is my whole code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery_v1.9.1.js"></script>
<script type="text/javascript">
var canvas = null;
var img = null;
var ctx = null;
var antX = 0,
antY = 0;
var canvasX = 0,
canvasY = 0;
var imageReady = false;
var img;
function onload() {
canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
img = document.getElementById("bg");
img.onload = loaded();
resize();
canvas.addEventListener("touchstart", doTouchStart, false);
document.addEventListener("click", function (e) {
if (!e) var e = e;
// e2.preventDefault();
canvasX = e.pageX - canvas.offsetLeft;
console.log("[mouseXY event] CanX array :" + canvasX);
canvasY = e.pageY - canvas.offsetTop;
console.log("[mouseXY event] CanY array:" + canvasY);
//alert("X :"+canvasX+"Y :"+canvasY);
antX = canvas.width / 2 - 48;
antY = canvas.height / 2 - 48;
//alert("X :"+antX+"Y :"+antY);
if (canvasX >= antX - 40 && canvasX <= antX + 40) {
// Is touchY between (antY - 10) and (antY + 10)?
if (canvasY >= antY - 40 && canvasY <= antY + 40) {
// The user touched the ant
alert("Touched on image");
}
}
});
}
function doTouchStart() {
alert("T");
}
function select_element() {
var offset = $div.offset();
var x = ev.clientX - offset.left;
var y = ev.clientY - offset.top;
alert("X :" + x + "Y :" + y);
}
function loaded() {
/* document.getElementById('divId').style.width = canvas.width / 2 - 48;
document.getElementById('divId').style.height = canvas.height / 2 - 48;
document.getElementById('divId').style.zIndex = "999"; */
//document.getElementById('divId');
imageReady = true;
setTimeout(update, 1000 / 60);
}
function resize() {
canvas.width = canvas.parentNode.clientWidth;
canvas.height = canvas.parentNode.clientHeight;
redraw();
}
function redraw() {
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
if (imageReady) {
ctx.drawImage(
img,
frame * 192,
0,
192,
192,
canvas.width / 2 - 48,
canvas.height / 2 - 48,
192,
192
);
}
}
var frame = 0;
function update() {
//console.log('hi');
redraw();
frame++;
if (frame >= 2) frame = 0;
setTimeout(update, 1000 / 10);
}
</script>
</head>
<body
onresize="onresize()"
onload="onload()"
style="position: absolute; padding: 0; margin: 0; height: 100%; width: 100%"
>
<img
class="clickable"
alt="simple1"
id="bg"
src="img/blink.png"
style="position: absolute; display: none; z-index: 1"
/>
<canvas id="gameCanvas" style="position: absolute"></canvas>
</body>
</html>
Any help would be much appreciated.
Does it work if you try:
<canvas id="can" style="position:absolute; z-index:999;">