How do I make an infinite JavaScript loop in HTML? - javascript

I am new to HTML programming, and I am trying to make a shooter game set in space.
I have this code so far:
<!DOCTYPE html>
<html>
<head>
<title>
Shooter
</title>
<style>
body{
background-color: blue;
}
</style>
</head>
<body>
<canvas width='1000' height='500' id='myCanvas'></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var radius = 1;
ctx.fillStyle = 'white'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.fillStyle = 'rgb(0, 0, 0)'
ctx.fillRect(1, 1, canvas.width - 2, canvas.height - 2)
var i=0;
var j=0;
for (i=0; i < 1000; i++){
for (j=0; j < 500; j++){
if (Math.random() > 0.999) {
ctx.beginPath();
ctx.arc(i, j, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'white';
ctx.fill();
ctx.lineWidth = 0;
ctx.strokeStyle = '#FFFFFF';
ctx.stroke();
ctx.closePath();
}
}
}
</script>
</body>
</html>
and I want to make a loop starting after the definition of radius and ending before the </script> tag, and neither draw=function() nor while(true) work, the entire script has no effect if I add them.

Related

For html canvas, how to use clip() with a text as a path?

I wrote the following code which is similar to my objective but falls short; because I want to fill inside the text in multiple colors; currently only in #FF00FF.
Playground
I think the problem is that I don't know how to use the text "ABC" as the clipping path. Please show me how to do it, or any answer equivalent for my objective.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas</title>
<script type="text/javascript">
function test() {
var canvas = document.getElementById('sample');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.beginPath();
for(let i=1;i<100;i++){
//mock1: ctx.fillStyle = "rgb(" + [i, i, i] + ")";
ctx.moveTo(0,5*i);
ctx.lineTo(380,5*i);
ctx.lineTo(300,5*i+3);
ctx.lineTo(0,5*i+3);
ctx.lineTo(0,5*i);
}
ctx.closePath();
ctx.clip();
ctx.font = "bold 72px 'Sans-selif'";
ctx.fillStyle = "#FF00FF";
ctx.fillText("ABC", 90, 60);
}
}
</script>
</head>
<body onLoad="test()">
<h2>Canvas</h2>
<canvas width="300" height="150" id="sample" style="background-color:yellow;">
</canvas>
</body>
</html>
The 2DCanvas API unfortunately doesn't expose the text's contour in a way it could be used as a Path2D or in methods like clip() or isPointInPath().
However for what you wish to do, you don't need a path, this can be done by using compositing instead of clipping:
var canvas = document.getElementById('sample');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
// draw the full lines first
ctx.beginPath();
for (let i = 1; i < 100; i++) {
ctx.moveTo(0, 5 * i);
ctx.lineTo(380, 5 * i);
ctx.lineTo(300, 5 * i + 3);
ctx.lineTo(0, 5 * i + 3);
ctx.lineTo(0, 5 * i);
}
ctx.fillStyle = "#00FF00";
ctx.fill();
// with this mode
// every previous pixel that is not under the next drawing
// will get cleared
ctx.globalCompositeOperation = "destination-atop"
ctx.font = "bold 72px 'Sans-serif'";
ctx.fillStyle = "#FF00FF";
ctx.fillText("ABC", 90, 60);
// reset to default mode
ctx.globalCompositeOperation = "source-over"
}
<canvas width="300" height="150" id="sample" style="background-color:yellow;"></canvas>

get area of a polygon

I'm trying to get the area of a polygone draw onclick in a canvas element
In the image above I try to get the area inside the red point which has a some opacity.
Is there anyway to do that "on the fly" which mean for each polygon draw.
I've already seen earcut.js which allow triangulation but I don't really understand how to get area whith this
var canvas = $('canvas');
var context = canvas[0].getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
$(canvas).attr({
width : this.width,
height: this.height
});
context.drawImage(imageObj,0,0);
};
imageObj.src = 'https://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
var clicks = [];
function drawPolygon(){
context.fillStyle = 'rgba(100,100,100,0.5)';
context.strokeStyle = "#df4b26";
context.lineWidth = 1;
context.beginPath();
context.moveTo(clicks[0].x, clicks[0].y);
for(var i=1; i < clicks.length; i++) {
context.lineTo(clicks[i].x,clicks[i].y);
}
context.closePath();
context.fill();
context.stroke();
};
function drawPoints(){
context.strokeStyle = "#df4b26";
context.lineJoin = "round";
context.lineWidth = 5;
for(var i=0; i < clicks.length; i++){
context.beginPath();
context.arc(clicks[i].x, clicks[i].y, 3, 0, 2 * Math.PI, false);
context.fillStyle = '#ffffff';
context.fill();
context.lineWidth = 5;
context.stroke();
}
};
function redraw(){
canvas.width = canvas.width; // Clears the canvas
context.drawImage(imageObj,0,0);
drawPolygon();
drawPoints();
};
canvas
.mouseup(function (e) {
clicks.push({
x: e.offsetX,
y: e.offsetY
});
redraw();
});
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>draw polygon with canvas</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<canvas width="600" height="400"></canvas>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
There is very simple algorithm to calculate area of polygon with given vertex coordinates: Shoelace formula
A = 1/2* Sum((x[i+1] + x[i]) * ([y[i+1] - y[i]))
(note indexes wrap in circular manner, so x[n]=x[0])
that might be implemented in a single loop.

Concentric circle with random colors in JS canvas (with loop)?

I am trying to draw concentric circles with javascript canvas with a loop. The circles have to be a random color each time they are drawn. I have tried to draw the circles with the code below but it didn't work. Thanks for your help!
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
while ( i=50 ; i < 5; i=i-5 ) {
context.beginPath();
context.arc(300, 300, i, 0, 2 * Math.PI, false);
//context.fillStyle = 'green';
//context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
}
//the code below worked for one circle
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
</script>
</body>
</html>
Multiple Typos
Three typographical type errors for your consideration:
The while loop is a for loop. In
while ( i=50 ; i < 5; i=i-5 )
replace while with for
The loop condition is false, so the loop never executes after fixing 1.
for( i=50; i < 5; i=i-5)
replace i < 5 with i > 5
The circles are off canvas and can't be seen. For demonstrations purposes only, replace
context.arc(300, 300, i, 0, 2 * Math.PI, false);
with, say,
context.arc(100, 100, i, 0, 2 * Math.PI, false);
and remove, or fully comment out, the "working" code example to remove syntax errors.
A working example using a line width of 3px:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
for ( i=50 ; i > 5; i=i-5 ) {
context.beginPath();
context.arc(100, 100, i, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill()
context.lineWidth = 3;
context.strokeStyle = '#003300';
context.stroke();
}
<canvas id="myCanvas" width="578" height="200"></canvas>

2048 in javascript: updating the canvas

I am in a computer science class at my high school, and for my final project, my partner and I have decided to make 2048. We are not going to have the tiles "move", but instead, the 4x4 board will have "tiles" that are have properties of the number and color of the "tile" as it appears on the board. We are able to get the x and y coordinates of a tile to change, but the canvas will not update. We have had this problem for two weeks now, and have tried everything, but nothing has worked. Our code is posted below.
Please keep in mind that as we have only used javascript for a couple months, and only to do very simple things, our understanding is limited. Thank you for your help.
<!DOCTYPE html>
<html lang = "en">
<body style="background-color:lightgrey;">
<title>2048</title>
<canvas id="myCanvas" width="410" height="410" style="border:1px solid #d3d3d3;">
</canvas>
<script>
var x = 10;
var y = 10;
document.addEventListener('keydown', function(event)
{
if(event.keyCode == 37)//left
{
x -= 100;
console.log("x:"+ x);
}
else if(event.keyCode == 38)//up
{
y -= 100;
console.log("y:"+ y);
}
else if(event.keyCode == 39)//right
{
x += 100;
console.log("x:"+ x);
}
else if(event.keyCode == 40)//down
{
y += 100;
console.log("y:"+ y);
}
});
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// grey rectangle
ctx.beginPath();
ctx.lineWidth = "2";
ctx.strokeStyle = "grey";
ctx.rect(5, 5, 400, 400);
ctx.stroke();
// blue rectangle
ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "blue";
ctx.rect(x, y, 100, 100);
ctx.stroke();
ctx.fillStyle = "blue";
ctx.fill();
</script>
</body>
</html>
What your game needs is a game loop. So the drawing needs to happen continously, at the moment you draw only one time at the beginning.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
function draw() {
// clear the canvas so the old rectangles are gone
ctx.clearRect(0, 0, c.width, c.height);
// grey rectangle
ctx.beginPath();
ctx.lineWidth = "2";
ctx.strokeStyle = "grey";
ctx.rect(5, 5, 400, 400);
ctx.stroke();
// blue rectangle
ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "blue";
ctx.rect(x, y, 100, 100);
ctx.stroke();
ctx.fillStyle = "blue";
ctx.fill();
}
// repeat game loop function forever, 30 times per second
window.setInterval(draw, 1000.0 / 30.0)
Notice the use of window.setInterval and ctx.clearRect.
Every time you want to update what is shown on the canvas, you have to 'Draw' again. Your code will run once when the page loads but never draws again so your changes to x and y are never seen.
I added a draw function here that is called on startup and after each keydown.
<!DOCTYPE html>
<html lang = "en">
<body style="background-color:lightgrey;">
<title>2048</title>
<canvas id="myCanvas" width="410" height="410" style="border:1px solid #d3d3d3;">
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = 10;
var y = 10;
document.addEventListener('keydown', function(event)
{
if(event.keyCode == 37)//left
{
x -= 100;
console.log("x:"+ x);
}
else if(event.keyCode == 38)//up
{
y -= 100;
console.log("y:"+ y);
}
else if(event.keyCode == 39)//right
{
x += 100;
console.log("x:"+ x);
}
else if(event.keyCode == 40)//down
{
y += 100;
console.log("y:"+ y);
}
draw();
});
function draw(){
ctx.clearRect(0, 0, c.width, c.height);
// grey rectangle
ctx.beginPath();
ctx.lineWidth = "2";
ctx.strokeStyle = "grey";
ctx.rect(5, 5, 400, 400);
ctx.stroke();
// blue rectangle
ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "blue";
ctx.rect(x, y, 100, 100);
ctx.stroke();
ctx.fillStyle = "blue";
ctx.fill();
}
draw();
</script>
</body>
</html>

Moving text inside canvas using html5

I am new to html5 development could anyone tell me how to make text to move one side to other horizontally inside canvas..
Here's an example of how to animate text back and forth across the screen:
<html>
<head>
<title>HTML 5 Animated Text</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var context;
var text = "";
var textDirection ="";
$(function()
{
context = document.getElementById("cvs").getContext("2d");
setInterval("animate()", 30);
textDirection ="right";
textXpos = 5;
text = "Animation!";
});
function animate() {
// Clear screen
context.clearRect(0, 0, 500, 500);
context.globalAlpha = 1;
context.fillStyle = '#fff';
context.fillRect(0, 0, 500, 500);
var metrics = context.measureText(text);
var textWidth = metrics.width;
if (textDirection == "right") {
textXpos += 10;
if (textXpos > 500 - textWidth) {
textDirection = "left";
}
}
else {
textXpos -= 10;
if (textXpos < 10) {
textDirection = "right";
}
}
context.font = '20px _sans';
context.fillStyle = '#FF0000';
context.textBaseline = 'top';
context.fillText ( text, textXpos, 180);
}
</script>
</head>
<body>
<div id="page">
<canvas id="cvs" width="500" height="500">
Your browser does not support the HTML 5 Canvas.
</canvas>
</div>
</body>
</html>
In action: http://jsfiddle.net/bS79G/
You can also use the canvas store(), translate() and restore() methods to animate the text.
suppose if you want to move the text from right side to left side, then you can use the following code snippet:
Refer site: http://www.authorcode.com/text-animation-in-html5/
var can, ctx, step, steps = 0,
delay = 20;
function init() {
can = document.getElementById("MyCanvas1");
ctx = can.getContext("2d");
ctx.fillStyle = "blue";
ctx.font = "20pt Verdana";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
step = 0;
steps = can.height + 50;
RunTextRightToLeft();
}
function RunTextRightToLeft() {
step++;
ctx.clearRect(0, 0, can.width, can.height);
ctx.save();
ctx.translate(can.width / 2, step);
ctx.fillText("Welcome", 0, 0);
ctx.restore();
if (step == steps)
step = 0;
if (step < steps)
var t = setTimeout('RunTextRightToLeft()', delay);
}

Categories