Why can't I draw a picture in canvas? - javascript

I tried to put a picture in the canvas, but it just doesn't appear. I've Googled it to find out what's wrong, unfortunately I still can't solve it.
Here's my code:
window.onload = function() {
var cnvs = document.getElementById("gc");
var ctx = cnvs.getContext("2d");
var img = new Image();
img.src = "/img/road.jpg";
ctx.drawImage(img, 0, 0);
};
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
.game-border {
display: flex;
justify-content: center;
justify-items: center;
}
#gc {
width: 100vmin;
height: 100vmin;
background-color: coral;
}
<div class="game-border">
<canvas id="gc"></canvas>
</div>

If you try to call drawImage() before the image has finished loading, it won't do anything. So you need to be sure to use the load event so you don't try this before the image has loaded:
var img = new Image(); // Create new img element
img.addEventListener('load', function() {
// execute drawImage statements here
ctx.drawImage(img,0,0);
}, false);
img.src = 'myImage.png'; // Set source path
Source: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images

Related

How can I set the wrapper of an element's height after the element has been created?

I created a wrapper in my HTML, .slider-wrapper, and using JavaScript, I created an image inside it, so far I've set the image's width to the .slider-wrapper's width and now I want the .slider-wrapper's height to be set to the image's height,
I've already tried doing sliderWrapper.style.height = sliderWrapper.children.offsetHeight in the move() method but it's not taking effect.
How can I set the .slider-wrapper's height to the image's height when the image is created?
document.addEventListener('DOMContentLoaded', function (event) {
let sliderWrapper = document.getElementsByClassName('slider-wrapper')[0];
class Image {
sliderWrapper = document.getElementsByClassName('slider-wrapper')[0];
constructor(_src) {
this.src = _src;
this.width = window.getComputedStyle(sliderWrapper).width;
this.move()
}
}
Image.prototype.move = function () {
let img = document.createElement('img');
img.setAttribute("src", this.src);
img.style.width = this.width;
img.classList.add('img');
sliderWrapper.appendChild(img);
sliderWrapper.style.height = sliderWrapper.children.offsetHeight;
}
let img = new Image('https://via.placeholder.com/150')
});
*{
padding: 0;
margin: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.slider-wrapper{
position: relative;
max-width: 800px;
margin: 70px auto;
border: 2px solid #ff0000;
}
<div class="slider-wrapper">
</div>
the class Image already exists in JS. create your own new class. Then use onload
document.addEventListener('DOMContentLoaded', function (event) {
let sliderWrapper = document.getElementsByClassName('slider-wrapper')[0];
class SlideImage {
sliderWrapper = document.getElementsByClassName('slider-wrapper')[0];
constructor(_src) {
this.src = _src;
this.width = window.getComputedStyle(sliderWrapper).width;
this.move()
}
}
SlideImage.prototype.move = function () {
const image = new Image();
image.src = this.src;
image.classList.add('img');
image.onload = function() {
sliderWrapper.appendChild(image);
sliderWrapper.style.height = image.height;
console.log(image.height)
}
}
new SlideImage('https://via.placeholder.com/150')
});
Use img.onload to check if the img has finished loading. Also use children[0].
document.addEventListener('DOMContentLoaded', function(event) {
let sliderWrapper = document.getElementsByClassName('slider-wrapper')[0];
class Image {
sliderWrapper = document.getElementsByClassName('slider-wrapper')[0];
constructor(_src, _id) {
this.src = _src;
this.id = _id;
//remove to get the actual proportions
// this.width = window.getComputedStyle(sliderWrapper).width;
this.move()
}
}
Image.prototype.move = function() {
let img = document.createElement('img');
img.setAttribute("src", this.src);
img.style.width = this.width;
img.classList.add('img');
sliderWrapper.appendChild(img);
img.onload = function() {
sliderWrapper.style.height = sliderWrapper.children[0].offsetHeight;
}
}
let img = new Image('https://via.placeholder.com/150')
});
* {
padding: 0;
margin: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.slider-wrapper {
position: relative;
max-width: 800px;
margin: 70px auto;
border: 2px solid #ff0000;
}
<div class="slider-wrapper">
</div>

Javascript Canvas: Drawing over picture

I have been having a problem with a drawing on a canvas. I want the user to be able to change the background on the canvas and I will eventually want to be able to type something in an input box and it will appear on the canvas in boxes. I have been trying to get more on the screen after they have choosen a background (which works fine), but when I try to add just a simple box I can't. I have been trying to do it in different parts of the code but doesn't work for me, and haven't been able to find a solution.
So what I am asking, is there a specific way you have to do it in order to have
a image (choosen with a select tag, which I already have working), and be able to draw a box ontop of the image choosen. Hope someone can explain to me how I will be able to do so!
function load(){
draw()
}
//Canvas change background
function draw(){
changeBackground("assets/images/1.jpg");
}
function changeBackground(imagePath){
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.onload = function(){
ctx.drawImage(img,0,0,954,507);
};
img.src=imagePath;
}
function background(){
var imageN = document.getElementById("imageselector").value;
console.log("Image picked as a Background: " + imageN)
changeBackground("assets/images/" + imageN + ".jpg");
}
Let this be a good foundation for your app!
Happy coding!
const canvas = document.querySelector("#canvas");
const context = canvas.getContext("2d");
const imageInput = document.querySelector("#imageInput");
const textInput = document.querySelector("#textInput");
const imageUrl = 'https://i.picsum.photos/id/944/600/600.jpg';
imageInput.value = imageUrl;
const state = {
image: null,
text: ''
}
const width = window.innerWidth;
const height = window.innerHeight;;
canvas.width = width;
canvas.height = height;
textInput.addEventListener("keydown", ({key}) => {
const value = textInput.value;
if(key === "Backspace") {
state.text = value.substring(0, value.length - 1);
}
else {
state.text = value + key;
}
render();
})
imageInput.addEventListener("input", () => {
getImage(imageInput.value)
.then(image => {
state.image = image;
render();
})
})
const render = () => {
clear();
drawBackground(state.image);
drawText(state.text);
}
const drawText = (text) => {
context.font = "40px Comic Sans";
context.fillStyle = "white";
const textMeasure = context.measureText(text);
context.fillText(text, width / 2 - textMeasure.width / 2, height / 5);
}
const clear = () => {
context.fillStyle = "white";
context.fillRect(0, 0, width, height);
}
const getImage = (imagePath) => new Promise((resolve, reject) => {
const image = new Image();
image.onload = function() {
resolve(image);
};
image.src = imagePath;
})
const drawBackground = (image) => {
context.drawImage(image, 0, 0, width, height);
}
getImage(imageInput.value)
.then(image => {
state.image = image;
render();
})
html, body {
margin: 0;
height: 100%;
box-sizing: border-box;
}
#box {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
#wrapper {
background: white;
}
#textInput, #imageInput {
width: 300px;
padding: 1rem;
background: transparent;
border: none;
}
#canvas {
position: absolute;
z-Index: -1;
}
<canvas id="canvas"></canvas>
<div id="box">
<div id="wrapper">
<input id="imageInput" type="text" placeholder="Enter src or dataUri of an image...">
<div>
<input id="textInput" type="text" placeholder="Enter text to show up...">
</div>
</div>
</div>
I just had to delay the text and boxes and then it worked :)

Canvas only being displayed on the first image of the slider or connected to the bottom of each image

So I tried to make it so that whenever an image is clicked it will draw a circle on a canvas. The image and the canvas are suppose to overlay. However, I have a problem when I have
cnvs.style.position = 'absolute'; active all of my canvas' are stacked on each other on the first image. So if I were to click other images the circle would be drawn on the first image but not on the image clicked. However, if I comment out cnvs.style.position = 'absolute'; the canvas is being connected to the bottom of the image instead of being overlaid. I need to make it so that each canvas and image are overlaid so that when one image is clicked a circle will appear. I'm thinking I have a css problem, but I'm not sure how to fix it.
document.body.onload = addElement;
function addElement() {
// image path
const imagePath = ['https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fen%2F8%2F84%2FAssociation_of_Gay_and_Lesbian_Psychiatrists_logo.jpg&f=1&nofb=1', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fstatic01.nyt.com%2Fnewsgraphics%2F2016%2F07%2F14%2Fpluto-one-year%2Fassets%2Ficon-pluto.png&f=1&nofb=1', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse4.mm.bing.net%2Fth%3Fid%3DOIP.oFxADNN67dYP-ke5xg7HbQHaHG%26pid%3DApi&f=1', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia.glassdoor.com%2Fsqll%2F1065746%2Felevation-church-squarelogo-1453223965790.png&f=1&nofb=1'];
for (const image of imagePath) {
// get the item id of an image
var slice = image.slice(26, 34);
var id = image;
var hdnName = document.getElementById("sendServ");
const img = document.createElement("img");
img.src = image;
img.classList.add("new");
img.id = slice;
const cnvs = document.createElement("canvas");
cnvs.classList.add("suiteiCanvas");
// cnvs.style.position = 'absolute';
cnvs.style.left = img.offsetLeft + "px";
cnvs.style.top = img.offsetTop + "px";
cnvs.style.display = 'none';
var ctx = cnvs.getContext("2d");
ctx.clearRect(0, 0, cnvs.width, cnvs.height);
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI, false);
ctx.lineWidth = 15;
ctx.strokeStyle = '#FF0000';
ctx.stroke();
var div = document.createElement("div");
var div1 = document.createElement("div");
div.id = id;
div1.id = '1';
div.classList.add("image");
img.onclick = function draw() {
cnvs.style.display = '';
hdnName.value = img.id;
};
cnvs.onclick = function remove() {
cnvs.style.display = 'none';
hdnName.value = null;
};
document.getElementById('suitei-slider').appendChild(div);
document.getElementById(image).appendChild(img);
document.getElementById(image).appendChild(cnvs);
}
}
// slick slider
canvas.suiteiCanvas{
height: auto;
width: auto;
max-height: 200px;
max-width: 150px;
margin-left: 100px;
margin-right: 100px;
border:3px solid rgb(20, 11, 11);
}
#draw-btn {
font-size: 14px;
padding: 2px 16px 3px 16px;
margin-bottom: 8px;
}
img.new {
height: auto;
width: auto;
max-height: 200px;
max-width: 150px;
margin-left: 100px;
margin-right: 100px;
border:3px solid rgb(20, 11, 11);
}
<div class="multiple-items" id="suitei-slider"></div>
<input type="hidden" id="sendServ">
You need to set your canvases in position: absolute inside a container in position: relative so that your canvases are still contained in the container. Since the containers are not in position: absolute, they don't overlay, but their content will, so your canvases will overlay with the images.
Then, you have to center you canvases (I suspect), so I set the canvases dimensions (for now it's hard coded) and fixed the x position of the circle.
I hope it is what you were looking for.
document.body.onload = addElement;
function addElement() {
// image path
const imagePath = ['https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fen%2F8%2F84%2FAssociation_of_Gay_and_Lesbian_Psychiatrists_logo.jpg&f=1&nofb=1', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fstatic01.nyt.com%2Fnewsgraphics%2F2016%2F07%2F14%2Fpluto-one-year%2Fassets%2Ficon-pluto.png&f=1&nofb=1', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse4.mm.bing.net%2Fth%3Fid%3DOIP.oFxADNN67dYP-ke5xg7HbQHaHG%26pid%3DApi&f=1', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia.glassdoor.com%2Fsqll%2F1065746%2Felevation-church-squarelogo-1453223965790.png&f=1&nofb=1'];
for (const image of imagePath) {
// get the item id of an image
var slice = image.slice(26, 34);
var id = image;
var hdnName = document.getElementById("sendServ");
const img = document.createElement("img");
img.src = image;
img.classList.add("new");
img.id = slice;
const cnvs = document.createElement("canvas");
cnvs.classList.add("suiteiCanvas");
// cnvs.style.position = 'absolute';
cnvs.style.left = img.offsetLeft + "px";
cnvs.style.top = img.offsetTop + "px";
cnvs.style.display = 'none';
cnvs.width = 150;
cnvs.height = 150;
var ctx = cnvs.getContext("2d");
ctx.clearRect(0, 0, cnvs.width, cnvs.height);
ctx.beginPath();
ctx.arc(75, 75, 50, 0, 2 * Math.PI, false);
ctx.lineWidth = 15;
ctx.strokeStyle = '#FF0000';
ctx.stroke();
var div = document.createElement("div");
var div1 = document.createElement("div");
div.id = id;
div1.id = '1';
div.classList.add("image");
img.onclick = function draw() {
cnvs.style.display = '';
hdnName.value = img.id;
};
cnvs.onclick = function remove() {
cnvs.style.display = 'none';
hdnName.value = null;
};
document.getElementById('suitei-slider').appendChild(div);
document.getElementById(image).appendChild(img);
document.getElementById(image).appendChild(cnvs);
}
}
// slick slider
.image {
position: relative; /* add this */
user-select: none; /* and this maybe */
}
canvas.suiteiCanvas{
height: auto;
width: auto;
height: 150px;
max-width: 150px;
/*margin-left: 100px;
margin-right: 100px;*/
border:3px solid rgb(20, 11, 11);
position: absolute; /* add this */
}
#draw-btn {
font-size: 14px;
padding: 2px 16px 3px 16px;
margin-bottom: 8px;
}
img.new {
height: auto;
width: auto;
max-height: 200px;
max-width: 150px;
/*margin-left: 100px;
margin-right: 100px;*/
border:3px solid rgb(20, 11, 11);
}
<div class="multiple-items" id="suitei-slider"></div>
<input type="hidden" id="sendServ">
Just in case you wonder what each line means here it is a more clean code and with comments on many lines... for my understanding you code is a little confuse. You should use more times functions to be more readable, etc.
let index = 0;
const display = "table"; // or "grid" if horizontal, but this migh depend where you place the rest of the code, cause i added the style to the body
const x = 0;
const y = 0;
const images = {
height: 50,
width: 50,
url: [
'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fen%2F8%2F84%2FAssociation_of_Gay_and_Lesbian_Psychiatrists_logo.jpg&f=1&nofb=1',
'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fstatic01.nyt.com%2Fnewsgraphics%2F2016%2F07%2F14%2Fpluto-one-year%2Fassets%2Ficon-pluto.png&f=1&nofb=1',
'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse4.mm.bing.net%2Fth%3Fid%3DOIP.oFxADNN67dYP-ke5xg7HbQHaHG%26pid%3DApi&f=1',
'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia.glassdoor.com%2Fsqll%2F1065746%2Felevation-church-squarelogo-1453223965790.png&f=1&nofb=1'
]
}
function createHTML() {
console.log('E: Execute & R: Request & I: Informative');
//loop to go true all images
document.body.style.display = display;
for (const image of images.url) {
//each image will correspond to a canvas element
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
//each canvas element will has is own properties (in this case all the same)
canvas.id = 'option' + [index];
canvas.height = images.height;
canvas.width = images.width;
canvas.style.padding = '10px';
//function to get the corresponded image of that particular canvas element
drawImages(canvas);
//add an event listener for when a user click on the particular canvas
canvas.addEventListener("click", optionClick, false);
//all html part was handle we can append it to the body
document.body.appendChild(canvas);
index++;
}
}
function drawImages(canvas) {
//we need to use the getContext canvas function to draw anything inside the canvas element
const ctx = canvas.getContext('2d');
const background = new Image();
//This is needed because if the drawImage is called from a different place that the createHTML function
//index value will not be at 0 and it will for sure with an heigher id that the one expected
//so we are using regex to remove all letters from the canvas.id and get the number to use it later
index = canvas.id.replace(/\D/g, '');
//console.log('E: Drawing image ' + index + ' on canvas ' + canvas.id);
//get the image url using the index to get the corresponded image
background.src = images.url[index];
//no idea why but to place the image, we need to use the onload event
//https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
background.onload = function() {
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
}
}
function drawX(canvas) {
const ctx = canvas.getContext('2d');
console.log('E: Placing X on canvas ' + canvas.id);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(images.width, images.height);
ctx.moveTo(images.height, 0);
ctx.lineTo(0, images.width);
ctx.closePath();
ctx.stroke();
}
function clear(canvas) {
console.log('E: clearing canvas ' + canvas.id);
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
drawImages(canvas);
}
function optionClick(e) {
log = true;
const canvas = document.getElementsByTagName('canvas');
for (const option of canvas) {
if (log) console.log('I: User clicked at option ' + e.target.id + ':' + option.id);
log = false;
if (e.target.id === option.id) {
console.log('R: Drawing request at canvas ' + option.id);
drawX(option);
} else {
console.log('R: Clearing request at canvas ' + option.id);
clear(option);
}
}
}
//We start by calling createHTML (that will handle with all HTML elements)
window.onload = createHTML;
canvas.suiteiCanvas {
height: auto;
width: auto;
max-height: 200px;
max-width: 150px;
margin-left: 100px;
margin-right: 100px;
border: 3px solid rgb(20, 11, 11);
}
#draw-btn {
font-size: 14px;
padding: 2px 16px 3px 16px;
margin-bottom: 8px;
}
img.new {
height: auto;
width: auto;
max-height: 200px;
max-width: 150px;
margin-left: 100px;
margin-right: 100px;
border: 3px solid rgb(20, 11, 11);
}
<body></body>

Creating thumbnail from existing base64 image

This is my first time using HTML canvas. I have been given a working camera that returns images as a base64 string. I am trying to pass this string to a new function that handles the image resizing(the actual dimensions aren't important right now as I am just testing the resizing).
Right now I am getting a blank image from my generateThumbnail function. Below I have attached an image of the output in the application, as well as an image of the console output.
For the first attached image, you will see 2 photos. The photo on the left is the original which is working correctly (it is all black because my webcam is covered). The photo on the right is the blank output when I attempt to resize.
generateThumbnail(imageData) {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let img = new Image();
img.onload = () => {
ctx.drawImage(img, 0, 0, 300, 300);
}
img.src = imageData;
let dataUrl = canvas.toDataURL("image/png");
console.log(imageData);
console.log(dataUrl);
return dataUrl;
}
image of taken photos
image of console output from thumbnail base64
Although your code is not working on the embedded fiddle, I think your problem is because the image has not loaded yet as you're returning dataUrl as soon as you execute your method.
dataUrl
should be returning inside img.onload method , maybe something like this will work?
** EDIT **
Make sure you set width and height of your canvas as well.
const generateThumbnail = (imageData) => {
let canvas = document.createElement("canvas");
canvas.width = 300;
canvas.height = 300;
document.querySelector(".canvas").appendChild(canvas);
let ctx = canvas.getContext("2d");
let img = new Image();
img.onload = () => {
ctx.drawImage(img, 0 , 0, 300, 300);
console.log(imageData);
console.log(dataUrl);
return dataUrl;
}
img.src = imageData;
let dataUrl = canvas.toDataURL("image/png");
document.querySelector(".image").appendChild(img);
}
window.onload = () => {
generateThumbnail(window.image_base64);
}
.canvas, .image {
position: absolute;
top: 0;
left: 0;
width: 300px;
height: 300px;
color: white;
}
.image { border: solid 1px white; }
.canvas {
left: 310px;
top: 0;
width: 300px;
height: 300px;
}
body {
background: purple;
}
<div class="image"></div>
<div class="canvas"></div>
<script>
window.image_base64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAMAAABOo35HAAAFU2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiPgogPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIgogICAgeG1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OqLeEy79kZWIoV/cinT0bfEmoLuIROKRYKyYnxmNoLelLSuy6Q4YlTrm1pCd1IPJ8qW0sidB8dXVfp55bHPkYtWsg9k4dTV8q/NUynpX7+m83LgQqlLYVZygBCRGPgUOXQbnVI/6AOstvelI14Us1KFn24xv4ZPePBc4WLQtdcMEaOStemuufhAwy+FnPA58FTWA+kjl2X0gu1DFGgzfdi4kJvfUTf6Zi18Ove9hLFanbkVnVjlbdjjXoB6h2u54FlBIpOvXdW0vfgHPOQL1Shl7ruOzVTS85DMLNate/YEnX/qzCzXLOZ6VXqwRHfxhBawFhRMq0q+3HV6GU6ZppgJLxjXn5CGfYDRpGIaR+eW6WAMwnA0sh7Ix0zTtNlspa0b3WCDH0KXObYaMv2vD0BP8qfP8kxpYm9b3hPK58WTGMFp3Sg5mQlIRa0d2c9w0Y76utStmmmZqqM2+09pw8pOJUtGf8taTpKF1+sV9ulSBxrT3XA0j31WBrtttHlkj9Gmn8YNNkf7NVcjRizVCnUra7O1bamWwrd2JtTXikPOrocShb3NPB752D7MlRgLJ5jVDLaRJ9VSiJTLLS1P1GkDnuvyi3ot7GsvIJJN9zWPLP+Lo9L8OvTKMxVOpVDymz2bFD9DuYMFakUo7WaAilNzU+I/7AcO/ivyDCkDVWfEAFiNX8P27DmvOZG+6HIzk6ZXAMZa15OlQyzoasJPdt2C9ncWkHS/70xzp3TdDddeMmdFI2Wi6y4p0FhdWUV9LzrX+2xuZ5Jn1tgjYti9u27Zt27G45wjvRliCFfq2vp+aIwW7I6Xv81On9WIjOAvg5NfkeH6OQxAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRAEQRCEn4D/BXJsajf86qhZAAAAAElFTkSuQmCC";
</script>

How to get JavaScript object to properly display rectangle on screen?

I'm doing an eCard for class and I have decided to create an animation using classes for the specific objects. The first thing I am doing is trying to get the background to draw a black rectangle across the whole canvas using Background.DrawBackgound. But nothing is working.
I have tried even copy/pasting the drawing code at the bottom to get it to draw but it will not draw. I have done classes in C# before but am a bit rusty so I am thinking I have some error somewhere in how I've set up my classes.
Here's the .js:
//james gossling multimedia for web design spring 2018
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
//game classes go here
Background = function() {
};
Background.prototype = {
DrawBackground: function() {
context.strokeStyle = 'black';
context.fillStyle = 'black';
context.beginPath();
context.rect(0,0,canvas.width,canvas.height);
context.stroke;
context.fill;
context.closePath();
},
};
Confetti = function() {
};
Confetti.prototype = {
};
Firework = function() {
};
Firework.prototype = {
};
UncleSam = function() {
};
UncleSam.prototype = {
};
Text = function() {
};
Text.prototype = {
};
//other functions
var ClearScreen = function() {
context.clearRect(0, 0, canvas.width, canvas.height);
};
var DrawObjects = function() {
//ClearScreen();
Background.DrawBackground();
};
var UpdatePositions = function(modifier) {
};
var Reset = function() {
};
//MAIN GAME LOOP FXN///////////////////
// The main game loop
var main = function() {
var now = Date.now();
var delta = now - then;
DrawObjects();
UpdatePositions(delta / 1000);
then = now;
//possibly do RESET
// Request to do this again ASAP
requestAnimationFrame(main);
};
// Cross-browser support for requestAnimationFrame
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
//START ECARD
var then = Date.now();
Background = new Background();
Reset();
main();
Background.DrawBackground();
and here's the .html:
<!DOCTYPE html>
<html>
<head>
<title>JamesG WebDesign</title>
<meta charset='UTF-8'>
<style>
body {
background-color: aqua;
}
h1 {
text-align: center;
}
h2 {
text-align: center;
}
p {
text-align: center;
}
#toMain {
margin-left: auto;
margin-right: auto;
text-align: center;
}
a {
font-size: 150%;
}
#canvas {
display: block;
margin: 0 auto;
background: #ffffff;
border: thin inset #aaaaaa;
}
#ResetAboveCanvas {
margin: 20px 0px 20px 450px;
}
</style>
</head>
<body>
<h2>James Gossling Multimedia for Web Design Spring 2018 </h2>
<p><strong>4th of July eCard</strong>
</p>
<canvas id='canvas' width='600' height='800'>
Canvas not supported
</canvas>
<script src='TestPC.js'></script>
<br>
<div id="toMain">
Back to Main
</div>
</body>
</html>
You are not invoking the functions fill and stroke.invoke the fill and stroke method should fix your problem
DrawBackground: function() {
console.log('here')
context.strokeStyle = 'black';
context.fillStyle = 'black';
context.beginPath();
context.rect(0,0,canvas.width,canvas.height);
context.stroke(); // invoke stroke
context.fill(); // invoke fill
context.closePath();
},

Categories

Resources