Hey guy's I'm trying to make a snake game in JS. Right now I'm making the function that will determine the direction of the snake, but at the moment I just want to log the keycode of any given key to the console, but it comes up as undefined? Why is this? I have the keycode stored into a variable before I log it? thanks for the help:)
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
//set canvas dimension equal to css dimension
canvas.width = 750;
canvas.height = 500;
//create stroke
ctx.strokeStyle = 'limegreen';
ctx.strokeRect(375, 250, 15, 15);
//create square
ctx.fillStyle = 'limegreen';
ctx.fillRect(375, 250, 15, 15);
//read user's direction
document.addEventListener('keydown', changeDirection);
function changeDirection(e) {
let code = e.keycode;
console.log(code);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<style>
body {
background-color: #333;
}
canvas {
background-color: #4d4d4d;
margin: auto;
display: block;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
width: 750px;
height: 500px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="script.js"></script>
</body>
</html>
Try e.keyCode instead of e.keycode
Related
Below here, the provided snippet for testing purpose.
The yellow(y) represent the canvas area, return "n" on click
The red(r) represent the click area, return "y" on click
The trouble(x) represent the error, return "y" when clicked
How to make it right?
yyyyyyyyyyyyyyy
yyrrrrrrrrrrryy
yyrrrrrrrrrrryy
yyxxxxxxxxxxxyy
yyyyyyyyyyyyyyy
const canvas = document.getElementById('test');
const context = canvas.getContext('2d');
testClicker();
function testClicker() {
const buttonz = new Path2D();
buttonz.rect(canvas.width / 2 - 125, canvas.height / 2 - 70, 250, 80);
context.fillStyle = 'red';
context.fill(buttonz);
var mouseEvent = (event) => {
// Check whether point is inside rect
const isPointInPath = context.isPointInPath(buttonz, event.offsetX, event.offsetY);
let a = isPointInPath ? 'y' : 'n';
alert(a);
}
canvas.addEventListener("click", mouseEvent, false);
}
* {
margin: 0px;
padding: 0px;
}
#test {
position: fixed;
top: 1%;
left: calc(50% - 150px);
width: 300px;
height: 100px;
background: yellow;
}
<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link rel="stylesheet" href="style.css">
<html>
<body>
<canvas id="test"></canvas>
</body>
<script src="main.js"></script>
</html>
You have a mismatch between the CSS setting of height of canvas (100px) and the canvas's attribute height (set to 150px by default).
You are using canvas.height as the basis for setting the path drawing on the canvas.
This snippet makes things match up by setting the height attribute of the canvas to 100.
const canvas = document.getElementById('test');
const context = canvas.getContext('2d');
testClicker();
function testClicker() {
const buttonz = new Path2D();
alert(canvas.height);
buttonz.rect(canvas.width / 2 - 125, canvas.height / 2 - 70, 250, 80);
context.fillStyle = 'red';
context.fill(buttonz);
var mouseEvent = (event) => {
// Check whether point is inside rect
alert(event.offsetY);
const isPointInPath = context.isPointInPath(buttonz, event.offsetX, event.offsetY);
let a = isPointInPath ? 'y' : 'n';
alert(a);
}
canvas.addEventListener("click", mouseEvent, false);
}
* {
margin: 0px;
padding: 0px;
}
#test {
position: fixed;
top: 1%;
left: calc(50% - 150px);
width: 300px;
height: 100px;
background: yellow;
}
<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link rel="stylesheet" href="style.css">
<html>
<body>
<canvas id="test" width="300" height="100"></canvas>
</body>
<script src="main.js"></script>
</html>
See MDN for further explanation of the difference between setting dimensions of the canvas using the width/height attributes and using CSS. If they differ you get scaling/distortion.
I have created a circle here so that when the screen is clicked, the circle will move there. And I also have a fixed point (vertex) that I want these two points to be the origin and destination of a line.
const coordinates = document.querySelector(".coordinates");
const circle = document.querySelector(".circle");
const result = document.querySelector(".result");
const numbers = document.querySelectorAll("p");
coordinates.addEventListener("click", e => {
circle.style.setProperty('--x', `${e.clientX}px`);
circle.style.setProperty('--y', `${e.clientY}px`);
})
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(50,100);
ctx.stroke();
canvas {
color: rgb(255, 255, 255);
}
.circle {
width: 20px;
height: 20px;
border-radius: 50%;
position: fixed;
--x: 47px;
left: calc(var(--x) - 10px);
--y: 47px;
top: calc(var(--y) - 10px);
background-color: white;
}
.bg {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #24232e;
}
.coordinates {
height: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="bg">
<div class="coordinates">
<canvas id="myCanvas" width="200" height="100" style=""></canvas>
</div>
</div>
<div class="circle">
</div>
</body>
</html>
How to do this with canvas?
! would appreciate <3
You can detect the mouse position on the canvas and draw a line to the coordinates. to get the canvas x and y of the mouse, you have to do some calculations because the site coordinates are a bit different than the canvas ones.
A more detailed description is here: https://stackoverflow.com/a/17130415/14076532
This will work only, if the canvas is big enough, logically...
Hope this helps:
const coordinates = document.querySelector(".coordinates");
const circle = document.querySelector(".circle");
const result = document.querySelector(".result");
const numbers = document.querySelectorAll("p");
coordinates.addEventListener("click", e => {
clicked(e);
circle.style.setProperty('--x', `${e.clientX}px`);
circle.style.setProperty('--y', `${e.clientY}px`);
})
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeStyle = "#de7270"; // change your color here NOTE: this will remain until you change it
ctx.moveTo(0,0);
ctx.lineTo(50,100);
ctx.stroke();
function clicked(event) {
ctx.save(); // some canvas-safety-stuff
ctx.beginPath();
let mousepos = getMousePos(event); // get the mouse position in "canvas-cooridnates"
ctx.clearRect(0,0, c.width, c.height) // erease the canvas
ctx.moveTo(0, 0);
ctx.lineTo(mousepos.x, mousepos.y); // draw the line to the mouse
ctx.closePath();
ctx.stroke(); // closing of the canvas-safety-stuff
ctx.restore();
}
function getMousePos (evt) {
var rect = c.getBoundingClientRect(), // abs. size of element
scaleX = c.width / c.width, // relationship bitmap vs. element for X
scaleY = c.height / rect.height; // relationship bitmap vs. element for Y
return {
x: (evt.clientX - rect.left) * scaleX, // scale mouse coordinates after they have
y: (evt.clientY - rect.top) * scaleY // been adjusted to be relative to element
}
}
canvas {
color: rgb(255, 255, 255);
}
.circle {
width: 20px;
height: 20px;
border-radius: 50%;
position: fixed;
--x: 47px;
left: calc(var(--x) - 10px);
--y: 47px;
top: calc(var(--y) - 10px);
background-color: white;
}
.bg {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #24232e;
}
.coordinates {
height: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="bg">
<div class="coordinates">
<canvas id="myCanvas" width="200" height="100" style=""></canvas>
</div>
</div>
<div class="circle">
</div>
</body>
</html>
I would like to create a curved side bar for my dashboard panel. I've tried 2 ways:
create a svg and path: that result was not good at all.
create with js: the result was good but it was rasterized :|
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Quadratic Bézier curve
ctx.beginPath();
ctx.moveTo(280, 0);
ctx.quadraticCurveTo(240, 90, 270, 150);
ctx.lineTo(320, 320);
ctx.lineTo(320, 0);
ctx.fillStyle = "#0984e3";
ctx.fill();
//
const hes = document.getElementById('hesam');
const ctxx = canvas.getContext('2d');
// Quadratic Bézier curve
ctxx.beginPath();
ctxx.moveTo(281, 0);
ctxx.quadraticCurveTo(240, 90, 280, 150);
ctxx.lineTo(320, 320);
ctxx.lineTo(320, 0);
ctxx.fillStyle = "#74b9ff";
ctxx.fill();
#canvas {
width: 100%;
height: 100%;
position: absolute;
float: right;
}
#hesam {
width: 100%;
height: 100%;
position: absolute;
float: right;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=">
<title></title>
</head>
<body>
<canvas id="canvas"></canvas>
<canvas id="hesam"></canvas>
</body>
</html>
https://codepen.io/hessamr/pen/vYLzePX
How can I have this result with vectorized and have quality to use bg of a side bar.
I'm trying to make a 'draw' app, which allows the user to draw something by dragging their mouse over a canvas.
I want to draw a 'pixel' where the user drags their mouse, however: The location of the mouse and the location where the 'pixels' get drawn are not the same.
I've searched all over the internet but I don't know what the difference is with my version and with theirs.
Image:
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drawer</title>
<script src="jquery-2.2.1.min.js"></script>
<script src="scripting/draw.js"></script>
</head>
<body>
<canvas id="drawGround" style="width: 500px; height: 500px; margin: 0 auto; border: 1px solid black;"></canvas>
</body>
</html>
Code:
$(document).ready(function() {
var drawSize = 3;
var canDrawCanvas = false;
const canvasID = "#drawGround";
document.onmouseup = function() {
canDrawCanvas = false;
};
$(canvasID).mousedown(function() {
canDrawCanvas = true;
});
$(canvasID).mousemove(function(event) {
if (canDrawCanvas) handleDrawing(event);
});
function handleDrawing(mouseEvent) {
var canvas = document.getElementById(canvasID.substring(1));
var context = canvas.getContext('2d');
context.fillRect(mouseEvent.pageX, mouseEvent.pageY, drawSize, drawSize);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="drawGround" style="width: 500px; height: 500px; margin: 0 auto; border: 1px solid black;"></canvas>
Instead of scaling the canvas object with the "style" attribute, you should use the "width" and "height"-attributes in the canvas-element.
<canvas id="drawGround" width="500px" height="500px" style="margin: 0 auto; border: 1px solid black;"></canvas>
Then use the offsetX and offsetY parameters instead of pageX and pageY to get the tip position of the mouse:
function handleDrawing(mouseEvent) {
var canvas = document.getElementById(canvasID.substring(1));
var context = canvas.getContext('2d');
context.fillRect(mouseEvent.offsetX, mouseEvent.offsetY, drawSize, drawSize);
}
I'm using a Webview in my android app. I'm placing a 2d canvas over a webgl canvas (webgl commented out here). Now, when I start up the app, half the time it draws the expected path, and half the time it draws nothing. Am I missing something? Could this be a caching problem or something?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cardboard container</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
margin: 0px;
overflow: hidden;
/*background-color: black;*/
}
#container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
display: none;
}
#stamp {
position: absolute;
top: 0px;
left: 160px;
width: 38px;
height: 38px;
background-color: red;
z-index: 0;
}
#bezier{
z-index: 2;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="stamp"></div>
<canvas id="bezier">Error creating bezier canvas</canvas>
<script src="js/third-party/threejs/three.js"></script>
<script src="js/third-party/threejs/StereoEffect.js"></script>
<script src="js/webgl.js"></script>
<script src="js/bezier.js"></script>
<script>
var consecutiveAbsentFrames = 6;
var totalFrames = 90;
var frameCount = 0;
var straightLineSpeed = 0.05;
var scaleFactor = 0.9;
var numGridPoints = 196;
var fovRadius = 9;
var fovXoffset = 0.5;
var gridPoints = []; // Points are an array [x0,y0,x1,y1,...]
var gridPoints2d = [];
var completePath = [];
var pathIndex = 0;
init();
function init() {
stamp = document.getElementById('stamp');
init2d();
}
function init2d(){
var b = document.getElementById('bezier');
b.width = window.innerWidth * scaleFactor * 0.5;
b.height = window.innerHeight;
var ctx=b.getContext('2d');
ctx.moveTo(0,0);
ctx.lineTo(100,100);
ctx.stroke();
}
</script>
</body>
</html>
EDIT:
Behavior is normal on a Moto X with Android 5.1, incorrect on Note 5 with 5.1.1