How can I achieve a camera/movement style similar to Slither.io? - javascript

I'm aware that this has been asked a few times, but they are all using other libraries and I need it to work using just P5.js and JavaScript.
I have a basic game setup where players join a room using Express and Socket.io and spawn in as a ship. I want there to be a playable map area, and for what the client sees to be a section of that map with the client's ship in the middle
How can I achieve this with the HTML canvas through p5.js?
One way I've tried is to map the ship's coordinates on the whole playable area to just the width of the client's browser. This works well, but doesn't have the client's ship in the centre so they just drift off the screen if the move around enough.
Here's a diagram to explain what I'm trying to achieve:
The black box represents the whole playable area (the map).
Each green circle is a ship and each red box represents the client who is controlling that ship and the section of the map that they can see

What you're looking for is the translate function:
specifies an amount to displace objects within the display window. The x parameter specifies left/right translation, the y parameter specifies up/down translation.
You want the player to be the centre of their screen, thus you should translate such that the player is at the centre.
translate(width/2 - player.x, height/2 - player.y);
I've put together a really simple example that should point you in the right direction. It's basically just a circle that you can move around a game world, I've added a couple rectangles in so it's obvious you're moving the player with the arrow keys:
let player;
function setup() {
createCanvas(400, 400);
player = {
x: width/2,
y: height/2
}
}
function draw() {
background(220);
translate(width/2 - player.x, height/2 - player.y);
rect(-100, 100, 50, 50);
rect(100, 50, 50, 50);
if (keyIsDown(LEFT_ARROW)) {
player.x--;
} else if (keyIsDown(RIGHT_ARROW)) {
player.x++;
} else if (keyIsDown(UP_ARROW)) {
player.y--;
} else if (keyIsDown(DOWN_ARROW)) {
player.y++;
}
ellipse(player.x, player.y, 10, 10);
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
Also, here's a link to the p5.js sketch

Related

Auto move cursor into a random location on the webpage via JS

I'm trying to create a simple web page to auto move cursor into a random positions.
I've tried and got the console to show random data, but I can't see the cursor moving.
Can someone please give me some hint to go further?
Should I also look into CSS transition ?
<!DOCTYPE html>
<html>
<head>
<title>Auto Mouse Mover</title>
</head>
<body>
<h1>Auto Mouse Mover</h1>
<p>This page automatically moves the mouse to a random location every 5 seconds.</p>
<script>
// Move the mouse to a random location
function moveMouse() {
var x = Math.floor(Math.random() * window.innerWidth);
var y = Math.floor(Math.random() * window.innerHeight);
window.moveTo(x, y);
console.log(x, y);
}
// Move the mouse every 5 seconds
setInterval(moveMouse, 1000);
</script>
</body>
</html>
You can't move the cursor with JS nor any web programming language, imagine all the security problems it would have.

How to add shapes to an empty webpage using Atom text editor?

I am new to programming but have completed most of the practice on the drawing and animation section on Khan Academy. Simply based on what I understand, I can place javascript code within a script tag placed between a body tag. However, when I opened my webpage, all I got was the style and the headings.
How can I animate or add shapes using the Atom text editor? I tried looking at Khan Academy and noticed that they also use processing.js, is that a reason my code won't run on my webpage? The code I will provide below will be my attempt to draw a sun growing larger and larger. The code inside the script tag is the exact and only code I needed to make the program run perfectly. I am not fully understanding if I am missing something. If not, can you help show the code for drawing a simple circle or rectangle(PS khan academy simply uses the rect and ellipse functions)?
Please note that I searched the stack for this and was unable to find a satisfying solution. Also, I used type=javascript in the script tags but the end result was the same when I clicked my webpage.
Thanks
MY code:
<!DOCTYPE html>
<html>
<head>
<title>Hello User</title>
<h1 class="text_color">I am blue text on a screen</h1>
</head>
<style>
body{
background-color:rgb(5,113,176);
font-family:arial;
font-size:20px;
}
.text_color{
color:blue;
font-family:arial;
}
</style>
<body>
<script>
noStroke();
// the beautiful blue sky
background(82, 222, 240);
// the starting size for the sun
var sunSize = 30;
//Animation part
draw = function() {
// The sun, a little circle on the horizon
fill(255, 204, 0);
ellipse(200, 298, sunSize, sunSize);
// The land, blocking half of the sun
fill(76, 168, 67);
rect(0, 300, 400, 100);
sunSize = sunSize+1;
};
</script>
</body>
</html>
First of all you have to link p5.js into your HTML Document, because you use function's that are declared in p5.js.
Try:
<script src="https://cdn.jsdelivr.net/npm/p5#0.10.2/lib/p5.js"></script>
At the bottom of <body>
then put your noStroke(); and Background(); into the funtion setup() because p5 variable and function names are not available outside setup(), draw(), mousePressed(), etc.
function setup(){
noStroke();
background(82, 222, 240);
}
Hope this will work for you.

Canvas arcTo() method

I am playing with HTML5 canvas , my book says that
latest browser supports arcTo method and it has capabilities to remove
arc() function .
My question is how?
Also I am confused with this example of arcTo , why its getting formed in this way can someone explain
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<canvas id="canvas" width="500" height="500" ></canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
var drawScreen = function(){
context.moveTo(0,0);
context.lineTo(100,200);
context.arcTo(350,350,100,100,20);
context.stroke();
}
drawScreen();
</script>
</body>
</html>
Here is some pseudocode explaining how the JavaScript code you posted works:
1) Get the canvas, and store it to variable 'canvas'
2) Get the 2d context of 'canvas', and store it to variable 'context'
3) Initialize a function, 'drawScreen', that takes no arguments, but runs the following instructions:
a) Move the pen to (0,0) on the canvas.
b) Draw a line from the pen's current position to (100, 100)
c) Draw an arc with a tangent line that passes through (350, 350) and the current pen position, and another tangent line that passes through (350, 350) and (100, 100), around a circle with radius 20.
d) Push the updated canvas to the screen.
4) Run the function 'drawScreen'
Believe it or not, you can use arcTo or a combination of other commands to do exactly the same thing arc does, albeit with more work, and there are numerous examples of this online.

User Editable Vector Shapes on a HTML5 Canvas

I want to be able to draw some basic vector shapes onto a HTML5 Canvas element.
The user should be able to use the mouse to directly draw any of these:
Square
Circle
Polygon
Onto the Canvas - these will later be used for hotspots on an image.
It is important that the user should be able to draw these vector shapes themselves by directly clicking within the canvas.
Is there an existing library that will help with this?
If there is no library, consider that I am an experienced web designer with an excellent knowledge of javascript, but I have very little experience with programming vectors. Where is the best place for me to go to fix this so I can build what I need?
fabricjs.com is your friend in this case ;)
You can use this little snippet for your first experiments...
for individual circles you must use:
mousedown (getCoordinates)
mouseup (getCoordinates)
Calculate the distance between these two points, that´s the radius.
Build an html options list for Square, Circle and Polygon.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<style>
canvas{border:1px solid #ccc;}
</style>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('click', function(evt) {
var mousePos = getMousePos(canvas, evt);
context.beginPath();
context.arc(mousePos.x,mousePos.y,5,0,2*Math.PI);
context.stroke();
}, false);
</script>
</body>
</html>

Vertical rotate image in Canvas

How can I vertically rotate an image using only Canvas (without WebGL etc.)?
I'm looking at something like -webkit-transform: rotateY(); in CSS3.
[Edit: Oops! I think I misunderstood your question. You want to flip with 3D effect, just without webGL.]
Yes, you can do 3D rotations in canvas without webGL.
Several canvas libraries offer 3D canvas rotation...
Take a look and K3D (NICE effects!): http://www.kevs3d.co.uk/dev/canvask3d/k3d_test.html
Take a look at GreenSock: http://www.greensock.com/css3/
If you don't want any libraries at all, check out K3D. It's license is liberal enough to allow you to pull out the rotating code you need.
.
.
[My original answer below is probably off-track of what you want--but I'll leave it here anyway]
Here's how to vertically flip a canvas image
When you want to flip vertically, you ironically are flipping on the horizontal axis.
To flip on the horizontal axis you use context.scale like this:
context.scale(1,-1); // flip vertically--using the HORIZONTAL axis !
Here's code and a Fiddle: http://jsfiddle.net/m1erickson/JBCGC/
<!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: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvasH=document.getElementById("canvasH");
var ctxH=canvasH.getContext("2d");
var img=new Image();
img.onload=function(){
// flip on the horizontal axis
// (causes upside down)
canvasH.width=img.width;
canvasH.height=img.height;
ctxH.save();
ctxH.scale(1,-1);
ctxH.translate(0,-img.height);
ctxH.drawImage(img,0,0);
ctxH.restore();
}
img.src="http://dl.dropbox.com/u/139992952/houseIcon.png";
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvasH" width=300 height=300></canvas>
</body>
</html>
You can try this -
// translate context to center of canvas
context.translate(canvas.width / 2, canvas.height / 2);
// rotate 45 degrees clockwise
context.rotate(Math.PI / 4);
The rotate transformation requires an angle in radians.
Reference
I like #markE answer, just figured I would post this one as well. It allows you to rotate the image to whatever angle you need.
function rotate(angle) {
ctxH.clearRect(0, 0, width, height);
ctxH.save();
ctxH.translate(width / 2, height / 2);
ctxH.rotate(angle * Math.PI / 180);
ctxH.drawImage(img, -width / 2, -height / 2);
ctxH.restore();
}
markE's Modified Demo (with animation)

Categories