Jquery and canvas code not working on same external file - javascript

I have been mucking about with a little bit coding using jquery and canvas (not together).
I have an external javascript file and in it contains;
$(document).ready(function() {
/*
NAME CHOOSER
*/
var carl = ['Sha', 'Shads', 'Cai', 'Moon', 'Sun', 'Staffy',];
var rosie = ['Mum',];
var prev;
$('button').click(function() {
prev = $('h2').text();
$('h2').empty().text(carl[Math.floor(Math.random() * carl.length)] + rosie[Math.floor(Math.random() * rosie.length)]).after('<p>' + prev + '</p>');
});
});
I also have some inline javascript which is for the canvas element;
<script>
var canvas = document.getElementById('draw');
if(canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 800, 500);
}
</script>
When separated by using inline javascript for the canvas and an external file for the jquery everything works fine and as expected.
When adding the inline canvas javascript to the external file the canvas element is not working but the jquery is. The javascript is loaded after the canvas element as my external javascript is linked just before the closing body tag and furthermore if I remove all jquery from the external file the canvas element begins to work again.
Why is this?
Thanks
EDIT
I have also now tried putting the canvas code inside jquerys document ready function and outside of it and it is still not working. I have wrapped the canvas code in an anonymous function still to no avail and have even tried selecting the canvas element with jquery itself like below;
var canvas = $('canvas')[0];
But it still doesn't want to know. Putting the canvas code before all the jquery then the canvas code executes but the jquery doesn't, I really am baffled! It doesn't bother me keeping it seperate but I would like to know why it is happening.
Thanks again.

This simple problems could be noted if you use the Browser Console. That's it! You can open the console pressing Ctrl+Shift+J:
In home page:
Error: Uncaught ReferenceError: $ is not defined
Solution: Link jQuery in your source
In namechooser page:
Error: Uncaught TypeError: Cannot read property 'getContext' of null
The problem:
You are trying to manipulate a div as it was a canvas, and you can't get the context of a div element. So this is your HTML:
<div id="wrap">
<h1>PORTFOLIO PROJECT :)</h1>
<button>Click here to generate a company name!</button>
</div>
Solution:
Change <div> for <canvas>
How to avoid future problems like this?
Use the browser console, that's it!

Ok, if I combine the code you have, above, it should look something like this: (see my jsFiddle for full context : http://jsfiddle.net/mori57/TqamB/ )
$(document).ready(function () {
/*
NAME CHOOSER
*/
var carl = ['Sha', 'Shads', 'Cai', 'Moon', 'Sun', 'Staffy'];
var rosie = ['Mum'];
var prev;
$('button').click(function () {
prev = $('h2').text();
$('h2').empty().text(carl[Math.floor(Math.random() * carl.length)] + rosie[Math.floor(Math.random() * rosie.length)]).after('<p>' + prev + '</p>');
});
var canvas = document.getElementById('draw');
if(canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 800, 500);
}
});
And, running within the context of jsFiddle, this works perfectly.
So, either you're not combining the two scripts properly (putting the canvas outside the document-ready block, for example, or somehow missing a closing brace), or there's something else amiss in your script file or markup.

Related

how to resize uploading image on to canvas

I am having trouble trying to resize the uploaded image on to my html for project. When I searched for a solution. The site https://www.w3schools.com/tags/canvas_drawimage.asp gave me an idea but I can't seem to wrap my head about the script. Am I misunderstanding something about the script?
<javascript>
function uploadForegroundImage(){
fileInput = document.getElementById("foregroundImageUpload");
image = new Image(fileInput);
image.onload = function() {
var c = document.getElementById("foregroundImageCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById(fileInput);
ctx.drawImage(img, 10, 10, 600, 400);
}
}
</javascript>
The code provided should work. If you are getting an error, make sure to load it from a URL that you have access to, or select it using an HTML input tag. Also I'm not aware of a "javascript" tag, it should be changed to "script"

Cannot read property 'complete' of null - complete

I would like to get this effect working on my webpage.
But I already tried this multiple times and failed every time. So, this is the reason why I am going to try it first on a local level. I copied everything you can see on the codepen.io webpage and replaced the both images with my pictures. Further, I added the id id="coverart" to the img and thats it.
But I get an error on this:
if (image.complete) {
The reason for it is:
Cannot read property 'complete' of null
But if I type this in my console:
document.getElementById('coverart');
I get the element back:
<img id="coverart" src="https://gamekeys-shop.de/wp-content/uploads/2017/01/coverart.png">
So, it cannot be null... What could be the reason for it and how can I fix it?
Here you can download the little html, css and js files.
EDIT:
If you insert alert(image), you will get null. If you replace this
if (image.complete) {
start();
} else {
image.onload = start;
}
with this
image.onload = start;
You will get the same null error... Why do I get null... It cannot be null?
There are few possible ways to improve it:
1) Just put your javascript file after the img tag.
2) Or run you code only when document will be loaded.
You can put your jquery definition onto bottom of body tag and use jquery $(document).ready() event like following.
$(document).ready(function(){
var image = document.getElementById("coverart");
if(image.complete){
console.log("loaded");
}
})
<img id="coverart" src="http://via.placeholder.com/350x150"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Since there is no need to wrap your code within a $(document).ready(function(){...}); or $(function(){...}); on codepen.So try doing that. You need jQuery to do that. So just add
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
to your HTML head.
$(document).ready(function(){
var image = document.querySelector('img');
var imageCanvas = document.createElement('canvas');
var imageCanvasContext = imageCanvas.getContext('2d');
...
imageCanvasContext.drawImage(image, 0, 0, width, height);
imageCanvasContext.globalCompositeOperation = 'destination-in';
imageCanvasContext.drawImage(lineCanvas, 0, 0);
}
});
Tried that for myself on localhost and it's working fine

How to generate 2d canvas from console to div

My code I have so far will generate into console.log. When I hit F12 it will display an img right there in the console.
How can I make it appear inside a div or somewhere more user appropriate than the console?
I tried making a <div class = "mylog"> to appropriate it inside canvas but I'm new sure how to code that together either.
Any suggestions & help would be super awesome!
I hope my question is straight forward.
(function(console) {
console.image = function(url) {
var image = document.createElement('img'),
canvas = document.createElement('canvas'),
canvasCtx = canvas.getContext('2d'),
//more code here//
})(console);
window.onload = function() {
console.image()
);
}
We will need to see more code to be any help because it seems that you're directly placing the function inside the console as an image. This gets rendered as 2d, and a canvas but will output only to console. You need to redo the code or show us more context to give you a better idea of what to change.

How to get this code to run in jsFiddle?

how to run this code in jsFiddle?
original code from Adam Khoury's site at http://www.developphp.com/view.php?tid=1262
I've experimented and am able to get the button to show and the canvas outline but can not get the object to animate from left to right when the button is clicked.
Here is my attempt to get it to run in jsFiddle at...
http://jsfiddle.net/Tn8xC/
function draw(x,y){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.save();
ctx.clearRect(0,0,550,400);
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect (x, y, 50, 50);
ctx.restore();
x += 1;
var loopTimer = setTimeout('draw('+x+','+y+')',30);
}
Thanks for any help.
JSFiddle's default settings have JavaScript run onLoad, or after the HTML loads.
This works well for most cases, except for when you use an on* attribute to execute JS inline, because the JS hasn't loaded, so you can't access its variables and methods.
You need to change onLoadto No wrap - in <head> in the left sidebar at the top: this places your JS in <script> tags in the head. The head loads before everything else (whatever you put in the HTML area), so when you use the onclick attribute to reference your draw() function, it has already been defined.
You can also use No wrap - in <body> because the JS will still be placed before the rest of your HTML, but placing it in the head should serve you well in most cases.
Had you checked the console, you would have seen ReferenceError: Can't find variable: draw, which would have told you that your JS hadn't loaded before you tried to access draw().
Demo

HTML5 Canvas not displaying in browser

I'm following this tutorial to learn HTML5 game development using javascript and jQuery. However, I've already come across a problem. When I run the HTML page that my js file is referenced from, nothing loads, and is just a blank screen. Here is the code for both files. Note that I haven't gotten very far in the tutorial.
index.html
<HTML>
<head>
</head>
<body>
<p>HTML5 and jQuery Tests</p>
<script type ="text/javascript" src="test.js"></script>
</body>
</HTML>
test.js
var CANVAS_WIDTH = 480;
var CANVAS_HEIGHT = 320;
var canvasElement = $("<canvas width='" + CANVAS_WIDTH +"' height='" + CANVAS_HEIGHT + "'></canvas>");
var canvas = canvasElement.get(0).getContext("2d");
canvasElement.appendTo('body');
var FPS = 30;
setInterval(function() {
update();
draw();
}, 1000/FPS);
function draw() {
canvas.fillStyle = "#000";
canvas.fillText("hello.", 50, 50);
}
Any help would be greatly appreciated! Also, am I allowed to ask questions about this code in this forum, on the same thread, or do I have to stat another?
Thanks!
~Carpetfizz
You don't have an update function to call. When the setInterval fires (which is ~32ms after the script loads), you're getting an error.
You need to add jQuery.
It's a library that was written to make working with HTML easier.
It needs to exist above where test.js does.
You can either download your own copy of it, or link to a copy elsewhere on the net - both will work fine.
$ is used by jQuery as a function to intelligently grab different kinds of items: HTML, JS, etc, and return JS objects with helpful functions for working with whatever you asked for.
Anyway, the update would still have caused an error, it was just second in line, behind the missing script.

Categories

Resources