Javascript script doesn't load in HTML - javascript

<!DOCTYPE html>
<html>
<head>
<title>Breakout</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<canvas width="900" height="450" class="canvas"></canvas>
<script src="scripts/base.js"></script>
</body>
</html>
This is the index file
*{
margin: 0;
padding: 0;
}
.canvas{
background-color: #b7b7b7;
}
This is the CSS file
var canvas = document.getElementsByClassName('canvas');
var context = canvas.getContext('2d');
context.beginPath();
context.drawRect(20,30,50,40);
context.fillStyle("#0022ff");
context.fill();
context.endPath();
And the javascript file.
I am trying to create a breakout game and I am following a tutorial from udemy. Unfortunately, it seems there is something wrong with this code, but I don't know what. I verified the code one thousand times and I haven't found anything.

That's because in your var canvas, you're calling document.getElementByClassName which will return an "array-like" object. So, I'd suggest you to use IDs instead of selecting using a class.

var context = canvas.getContext('2d'); should be var context = canvas[0].getContext('2d'); because you're using document.getElementsByClassName which will return a collection of all the elements with that class name. and you want the context of the first one.
context.drawRect should be context.rect.
context.fillStyle is not a function it should be context.fillStyle = "#0022ff";
context.endPath(); should be context.closePath();
In your case you don't need context.beginPath(); and context.closePath();. context.rect already creates the path.
var canvas = document.getElementsByClassName('canvas');
var context = canvas[0].getContext('2d');
context.rect(20, 30, 50, 40);
context.fillStyle = "#0022ff";
context.fill();
* {
margin: 0;
padding: 0;
}
.canvas {
background-color: #b7b7b7;
}
<canvas width="900" height="450" class="canvas"></canvas>

Use fillRect instead of drawRect:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.fillRect(20,30,50,40);
ctx.endPath();
</script>

Related

Some problems while uploading sprite to canvas in JS

`Hello! I have a problem with uploading an image to a canvas element in JS. I saved the image to some folder in my project, then I tried to upload it with the classic function, but then I faced that there is no errors, but my image is not displayed. Help me, please. All code and screenshots are further:
Code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Game of Drones</title>
<link rel="stylesheet" href="S:\Coding\JS\UAVGame\CSS\style.css">
</head>
<body>
<canvas id="field" width="800px" height="600px"></canvas>
<script src="S:\Coding\JS\UAVGame\JS\main.js"></script>
</body>
</html>`
CSS:
#field {
position: absolute;
left: 22%;
border: 9px grey double;
width: 800px;
height: 600px;
background: rgb(8, 2, 63);
}
JS:
let field = document.querySelector("#field");
let ctx = field.getContext("2d");
let UAV = new Image();
UAV.src = "S:/Coding/JS/UAVGame/OTHER/IMAGES/UAVBASED.png";
class Star {
constructor(xCoord, yCoord, radius) {
this.x = xCoord;
this.y = yCoord;
this.R = radius;
}
draw() {
ctx.fillStyle = "grey";
ctx.beginPath();
ctx.arc(this.x, this.y, this.R, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
}
}
let stars = [];
function drawScene() {
ctx.drawImage(UAV, 250, 250);
}
drawScene();
Screen of project structure
I don't know even what I have to try, because I use classic functions with a classic bundle of parameters, so I assume, that there is some magic, which makes me face that problem.`
Try calling drawScene on image onload event like below
UAV.onload = function(){
drawScene();
}
Also verify the path of image. I would suggest using absolute path like
UAV.src = "../OTHER/IMAGES/download.png";

Can't get HTML/Javascript Canvas to work [duplicate]

How to fill the whole HTML5 <canvas> with one color.
I saw some solutions such as this to change the background color using CSS but this is not a good solution since the canvas remains transparent, the only thing that changes is the color of the space it occupies.
Another one is by creating something with the color inside the canvas, for example, a rectangle(see here) but it still does not fill the whole canvas with the color (in case the canvas is bigger than the shape we created).
Is there a solution to fill the whole canvas with a specific color?
Yes, fill in a Rectangle with a solid color across the canvas, use the height and width of the canvas itself:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
canvas{ border: 1px solid black; }
<canvas width=300 height=150 id="canvas">
If you want to do the background explicitly, you must be certain that you draw behind the current elements on the canvas.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Add behind elements.
ctx.globalCompositeOperation = 'destination-over'
// Now draw!
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
You can change the background of the canvas by doing this:
<head>
<style>
canvas {
background-color: blue;
}
</style>
</head>
let canvas = document.getElementById('canvas');
canvas.setAttribute('width', window.innerWidth);
canvas.setAttribute('height', window.innerHeight);
let ctx = canvas.getContext('2d');
//Draw Canvas Fill mode
ctx.fillStyle = 'blue';
ctx.fillRect(0,0,canvas.width, canvas.height);
* { margin: 0; padding: 0; box-sizing: border-box; }
body { overflow: hidden; }
<canvas id='canvas'></canvas>
We don't need to access the canvas context.
Implementing hednek in pure JS you would get canvas.setAttribute('style', 'background-color:#00F8'). But my preferred method requires converting the kabab-case to camelCase.
canvas.style.backgroundColor = '#00F8'
You know what, there is an entire library for canvas graphics. It is called p5.js
You can add it with just a single line in your head element and an additional sketch.js file.
Do this to your html and body tags first:
<html style="margin:0 ; padding:0">
<body style="margin:0 ; padding:0">
Add this to your head:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
<script type="text/javascript" src="sketch.js"></script>
The sketch.js file
function setup() {
createCanvas(windowWidth, windowHeight);
background(r, g, b);
}

Can't display canvas object

Guys Here is a function which should display a red ball on the frame, but it isn't doing so, I am watching a tutorial to do that, I am doing everything exactly as he does but I can't figure out what is the problem here.. Please I need to know this. If somebody can understand please help..
var canvas,ctx,w,h,game=true;
var ball;
var BALL = function(x,y){
this.x = x;
this.y = y;
this.color = "red";
this.radius = 10;
this.vx = 3;
this.vy = -4;
}
window.onload = init;
function init() {
canvas = document.getElementById("canvas");
w = canvas.width;
h = canvas.height;
ctx = canvas.getContext('2d');
ball = new BALL(w/2,h/2+50);
beginGame();
}
function beginGame(){
if(game){
ctx.clearRect(0,0,w,h);
ball.x+=ball.vx;
ball.y+=ball.vy;
if((ball.x+ball.radius)+ball.vx>w || (ball.x-ball.radius)+ball.vx<0){
ball.vx = -ball.vx;
}
ctx.fillStyle = ball.color;
ctx.beginPath();
ctx.arc(ball.x,ball.y,ball.radus,0,2*Math.PI,true);
ctx.closePath();
ctx.fill();
window.requestAnimationFrame(beginGame);
}else{
//Game Over
}
}// End of beginGame function
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>არკანოიდი</title>
<script src='tools.js'></script>
<script src='jquery-1.11.2.min.js' language='javascript' > </script>
<style>
canvas {
border: 1px solid silver;
}
</style>
</head>
<canvas id="canvas" width="800" height="600"></canvas>
<body>
</body>
</html>
I don' know if it will fix everything but your canvas is outside of your body tags.
for script tags:
1. don't use language='javascript'. this is not needed.
2. If you do want to explicitly declare it as javascript, then use type="text/javascript". This is automatically the case, so you don't even need to do that.
3. Put the canvas inside the body tags.
4. use window.addEventListener("load", init) instead of window.onload(init)
5.inside startgame function:
function beginGame()
{
// previous lines omitted...
ball = new BALL(x, y);
// other lines here...
}

js getContext stops further code from executing

I have a working getContext in my JavaScript code, but for some reason nothing is executed after this method. Here, I added two alerts and only one of them runs:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas"
width="0"
height="0"
style="border:5px solid #888888; fill: solid #DDDDDD;"
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
// basic vars
var squareDim = 25;
var screenWidth = 10;
var screenHeight = 20;
// setting up the canvas
var canvas = document.getElementById("myCanvas");
canvas.width = screenWidth * squareDim;
canvas.height = screenHeight * squareDim;
alert(1)
var ctx = c.getContext("2d");
alert(2);
// draw a single square
function putSquare(color, x, y) {
ctx.fillStyle = color;
ctx.fillRect(x * squareDim, y * squareDim, squareDim, squareDim);
}
for (i=0; i<screenHeight; i++) {
putSquare("#FF0000", i, 0);
}
</script>
</body>
Does anyone have an idea where did I screw up?
You're calling c.getContext(...), you have no c variable declared - you need to call this on canvas instead:
var ctx = canvas.getContext('2d');
In future you can debug things like this in your browser's JavaScript console. In your JavaScript console, you'll see that your code here is throwing the following error:
Uncaught ReferenceError: c is not defined
See: How to open the JavaScript console in different browsers?

Iteratively change the fillStyle color in canvas while drawing a fractal

I'm using the following code to generate a Pythagoras fractal tree using HTML5 canvas element:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script src="jquery.js" type="text/javascript"></script>
<style>
#sketch
{
border: 1px solid black;
}
</style>
<script type="text/javascript">
window.onload = function()
{
var canvas = document.getElementById("sketch");
var context = canvas.getContext("2d");
context.fillStyle = "rgba(0, 0, 200, 0.5)";
context.beginPath();
context.moveTo(450,550);
context.lineTo(450,450);
context.lineTo(550,450);
context.lineTo(550,550);
context.fill();
fractal(context,[450,550],[450,450],[550,450],[550,550],5);
};
function fractal(context,P1,P2,P3,P4,depth)
{
context.fillStyle = "rgba(0,0,200,"+(depth/8).toString()+")";
context.save();
if(depth < 0)
{
return null;
}
/*Find C*/
C = divide(add(divide(add(P1,P2),2),divide(add(P3,P4),2)),2);
var V1 = divide(minus(C,P1),length(C,P1));
var V2 = divide(minus(C,P4),length(C,P4));
var P6 = add(P2,multiply(V2,length(P1,P2)/Math.sqrt(2)));
var P7 = add(P6,multiply(V1,length(P1,P2)/Math.sqrt(2)));
var P5 = add(P2,multiply(V1,length(P1,P2)/Math.sqrt(2)));
var P9 = add(P3,multiply(V1,length(P1,P2)/Math.sqrt(2)));
var P8 = add(P9,multiply(V2,length(P1,P2)/Math.sqrt(2)));
context.moveTo(P2[0],P2[1]);
context.lineTo(P6[0],P6[1]);
context.lineTo(P7[0],P7[1]);
context.lineTo(P5[0],P5[1]);
context.fill();
context.moveTo(P5[0],P5[1]);
context.lineTo(P8[0],P8[1]);
context.lineTo(P9[0],P9[1]);
context.lineTo(P3[0],P3[1]);
context.fill();
fractal(context,P2,P6,P7,P5,depth-1);
fractal(context,P5,P8,P9,P3,depth-1);
}
function multiply(v, num){
return [v[0]*num, v[1]*num];
}
function divide(v, num){
return [v[0]/num, v[1]/num];
}
function add(a, b){
return [a[0]+b[0], a[1]+b[1]];
}
function minus(a, b){
return [a[0]-b[0], a[1]-b[1]];
}
function length(a, b){
return Math.sqrt(Math.pow(a[0] - b[0],2) +
Math.pow(a[1] - b[1],2));
}
</script>
<title>Square</title>
</head>
<body>
<canvas id="sketch" height="1000" width="1000"></canvas>
</body>
</html>
I'm changing the opacity value with every iteration. But I don't see it in the result.
How can this be fixed??
You were really close to the right solution. Look here:
http://jsfiddle.net/mbessey/Wj4VH/
The key difference here is calling beginPath() before starting the moveTo() and lineTo() for each square. So, instead of:
context.moveTo(P2[0],P2[1]);
context.lineTo(P6[0],P6[1]);
context.lineTo(P7[0],P7[1]);
context.lineTo(P5[0],P5[1]);
context.fill();
context.moveTo(P5[0],P5[1]);
context.lineTo(P8[0],P8[1]);
context.lineTo(P9[0],P9[1]);
context.lineTo(P3[0],P3[1]);
context.fill();
You want:
context.beginPath()
context.moveTo(P2[0],P2[1]);
context.lineTo(P6[0],P6[1]);
context.lineTo(P7[0],P7[1]);
context.lineTo(P5[0],P5[1]);
context.fill();
context.beginPath()
context.moveTo(P5[0],P5[1]);
context.lineTo(P8[0],P8[1]);
context.lineTo(P9[0],P9[1]);
context.lineTo(P3[0],P3[1]);
context.fill();
What you were doing was essentially creating one large path with all the squares in it and then filling it all with the same color.
Check This I have changed the opacity of the canvas itself ,making it simple and easy to achieve the target.
Adding rgba(0, 0, 200, 1) and
#sketch
{
border: 1px solid black;
opacity: 0.3;
}
will suffice what you want

Categories

Resources