My Html canvas is null. Really annoying - javascript

i used a udemy course to make a simple pong game.
I am now recreating it again as practice and i keep getting the error canvas is null. Any Help?
<html>
<canvas id="gamecanvas" width="600" height="800"></canvas>
<script>
var canvas = null;
var Context = null;
window.onload = function(){
canvas.document.getElementById("gamecanvas");
Context.canvas.getContext("2d");
drawEverything();
}
function drawEverything() {
Context.fillStyle = "black";
Context.fillRect(0,0,canvas.width,canvas.height);
Context.fillStyle = "white";
Context.fillRect(0,360,20,80);
Context.fillStyle = "white";
Context.fillRect(580,360,20,80);
Context.fillStyle = "green";
context.beginpath();
context.arc(0,0,10,10,Math.PI*2,true);
context.fill();
}

That is because you set it to null! Change
canvas.document.getElementById("gamecanvas");
To
canvas = document.getElementById("gamecanvas");
Otherwise, you never set canvas.

You should do like this.
canvas = document.getElementById("gamecanvas");
Context = canvas.getContext("2d");

You set canvas to null so of course it will be null. This should help.
canvas = document.getElementById("gamecanvas")
context = canvas.getContext("2d");

Related

How can I make background color of canvas white with JavaScript?

What I want to do
I want to know how to make background color white.
I built a drawing app with canvas. You can download the canvas image you have drawn by clicking the Download button. But its background color is black (technically transparent).
How can I change it to white?
What I tried
I added the following code to my code, but it didn't work well. I couldn't draw anything.
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
Here is my code
const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#BADA55';
...
function draw(e) {
if (!isDrawing) return;
console.log(e);
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
...
}
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mousemove', draw);
...
downloadBtn.addEventListener('click', downloadImage);
function downloadImage() {
if (canvas.msToBlob) {
const blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob, filename);
} else {
downloadLink.href = canvas.toDataURL('image/png');
downloadLink.download = filename;
downloadLink.click();
}
}
I want to make background color of downloaded image white.
You can use the following code to set background color of canvas.
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "green";
context.fillRect(0, 0, canvas.width, canvas.height);
canvas{ border: 1px solid black; }
<canvas width=300 height=150 id="canvas">
On a canvas you can use getAttribute() to retrieve the dimension. Look at my snippet:
let canvas = document.getElementById('canvas');
let cheight = parseInt(canvas.getAttribute("height"));
let cwidth = parseInt(canvas.getAttribute("width"));
let context = canvas.getContext('2d');
context.fillStyle = "green";
context.fillRect(0,0,cwidth,cheight);
<canvas width="200" height="200" id="canvas">
In your draw() function you need to add specifically the background like this:
const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#BADA55';
ctx.fillStyle = "#ffffff"; //HERE, use HEX format in 6 digits
ctx.fillRect(0, 0, canvas.width, canvas.height); //HERE
...
function draw(e) {
...
}
Why?
You need to draw the background before everything, otherwise drawing the background over and over, or also above everything would result in the white rectangle overlapping everything on your canvas.
Here is a LIVE DEMO.

HTML5 Canvas: Not drawing

I'm currently creating a simple program using HTML Canvas and Javascript. All that I need to happen is for a ball to be drawn at coordinates on the canvas and then move around using some velocity variables etc.
The issue is, I've created a Ball object as I intend to have multiple balls on screen at a time, however nothing is showing on my canvas.
I've read over this a few times, I'm receiving no errors so I'm struggling to figure out what's happening with this.
EDIT:
I've added a console log to check the drawSelf() is running, which it is but still no error/result
CODE
<!DOCTYPE html>
<html>
<head>
<title>Bouncing Ball</title>
</head>
<script>
var Date
var canvas;
var ctx;
var dx=5;
var dy=5;
function init(){
canvas = document.getElementById('game');
ctx = canvas.getContext('2d');
setInterval(draw,10);
console.log("Initialised: " + new Date());
}
function Ball(x, y, dx, dy){
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.drawSelf = function () {
ctx.beginPath();
ctx.fillStyle = "#4286f4";
ctx.arc(this.x,this.y,20,0,Math.PI*2,true);
ctx.closePath();
console.log("Ball is drawing self!");
if(this.x<0 || this.x>800){
dx=-dx;
}
if(this.y<0 || this.y>800){
dy=-dy;
}
this.x+=this.dx;
this.y+=this.dy;
}
this.getX = function () {
console.log("X:" + this.x);
console.log("Y:" + this.y);
}
}
//Creating Ball object.
let ball1 = new Ball(400, 400, 5, 5);
function draw(){
ball1.drawSelf();
}
</script>
<body onLoad="init()">
<div id="canvas-area">
<canvas id="game" width="800" height="800"></canvas>
</div>
</body>
<html>
You forgot to add ctx.stroke() or ctx.fill(), taken from the Mozilla docs
this.drawSelf = function () {
ctx.beginPath();
ctx.fillStyle = "#4286f4";
ctx.arc(this.x,this.y,20,0,Math.PI*2,true);
ctx.stroke();
ctx.closePath();
console.log("Ball is drawing self!");
if(this.x<0 || this.x>800){
dx=-dx;
}
if(this.y<0 || this.y>800){
dy=-dy;
}
this.x+=this.dx;
this.y+=this.dy;
}
Also sidenote, since you don't set the background every draw, your canvas will just add the ball to it's current state, resulting in a cool pattern, but something you probably don't want. To fix this, make this your draw method.
function draw(){
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ball1.drawSelf();
}
EDIT: Instead of using setInterval I recommend using requestAnimationFrame. You can read more about it here

Why is nothing appearing on my canvas?

I am such a noob and I have no idea why nothing is appearing on my canvas. Can someone help me out? I wanted to have a black box on my canvas, that was the intention anyway.
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 1040;
canvas.height = 400;
canvas.style.display='block';
canvas.style.marginLeft="auto";
canvas.style.marginRight="auto";
var mainFunction= function(){
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.closePath();
ctx.fill();
requestAnimationFrame(mainFunction);
};
mainFunction();
You have created a <canvas> element but have not attached it anywhere in the DOM. Perhaps you want something like
document.body.appendChild(canvas);
or another suitable container.
Basically, you do not have an attached canvas to the DOM.
Create a html file with <canvas id="root"></canvas>;
var canvas = document.getElementById("root");

"var canvas = document.getElementById("canvas")" can't be a global variable?

I made the following script. When I push the button, the word "blood" moves, and push the button and it stops.
This script worked in Chrome but when I move the following scripts to the TOP line. (between var flag; and window.setInterval), an error happens saying
uncaught typeerror cannot call method 'getcontext' of null"
would you explain why it happens please?
var canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d");
var y = 100;
var flag = false;
window.onload = setInterval(function(){
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red";
ctx.font = "50px Helvetica";
ctx.fillText("blood", 200, y);
if(flag){
y++;
}
}, 30);
function start(){
flag = true;
}
function stop(){
flag = false;
}
If you run your code in a script element at the end of the html body, you can ensure that it doesn't try to get the canvas context before the DOM is ready. Also, I made an optimization to your code to cache the DOM lookup:
<html>
<head>
<title>Canvas Scrolling Text</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
var y = 100;
var flag = false;
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
setInterval(function() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red";
ctx.font = "50px Helvetica";
ctx.fillText("blood", 100, y);
if(flag)
y++;
}, 30);
function start()
{
flag = true;
}
function stop()
{
flag = false;
}
start();
</script>
</body>
Here's a working jsFiddle.
If you move it out of the onload function, then the DOM elements (specifically your canvas) don't exist yet. See https://stackoverflow.com/a/15564394/1370556 for more information on DOM content loaded events.

Why won't canvas draw?

I've looked over this code every way I can, and I'm not seeing what's tripping me up. This is my first night looking into canvas, and my first night messing with JS outside of Codecademy, so I'm sure it's something fundamental that I missed at some point.
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(75, 50);
ctx.lineTo(100, 75);
ctx.lineTo(100, 25);
ctx.fill();
}
}
Here's the fiddle
You forgot to call draw function. Take a look here.
draw();
code looks like this
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(75,50);
ctx.lineTo(100,75);
ctx.lineTo(100,25);
ctx.fill();
}
}
draw();

Categories

Resources