I have trouble connecting js files using html - javascript

What I want do find out is how I can make this work so it makes a red box at location 100,100, using a function as my main function and another function to draw the image but I want it to be in a different js file.
2 js files and 1 html file.
Code
//HTML code
<!DOCTYPE html>
<html lang ="en">
<head>
<meta charset="UTF-8">
<title>Prufa Einar</title>
</head>
<body>
<canvas id = "myCanvas" width="600" height = "600"
style ="border: 1px solid black;">
<script type = "text/javascript" src "draw.js"></script>
<script type = "text/javascript" src "main.js"></script>
<script type = "text/javascript">
main();
</script>
</body>
</html>
//first js.file
var canvas;
var ctx;
var main = function()
{
canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
draw(ctx);
};
//second js file
var draw = function(ctx)
{
{
ctx.fillStyle = "Red";
ctx.fillRect(100,100,20,20);
}
};

Looks like you need equal sign after src.
src=""
and canvas out of head into body instead

Related

canvas.getContext("2d"); not working

I am getting the following Error
Error: Uncaught TypeError: Cannot read property 'innerHTML' of null
at script.js:1
I have tried everything I could think of but nothing works.
var canvas = document.getElementById("can").innerHTML;
var ctx = canvas.getContext("2d");
ctx.fillStyle = ("green");
ctx.fillRect(0, 0, 300, 200);
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
</head>
<body>
<script src="script.js"></script>
<!-- Canvas -->
<canvas id="can" width="300" height="200" style="border:4px solid red;">
</canvas
</body>
</html>
Okay there are two serious errors.
You're trying to get the element before the DOM is fully loaded. Therefore the canvas note is not reachable. See addEventListener
and DOMContentLoaded.
Remove .innerHTML. getContext appends on the node not on the content.
document.addEventListener('DOMContentLoaded', function() {
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 300, 200);
});
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
</head>
<body>
<script src="script.js"></script>
<!-- Canvas -->
<canvas id="can" width="300" height="200" style="border:4px solid red;">
</canvas>
</body>
</html>
1. Script error when using canvas
Use var canvas = document.getElementById("can");
Not var canvas = document.getElementById("can").innerHTML();
See W3C - Canvas
2. Add an event listener when the document is ready, then execute your script
See W3C - DOM Event Listener example
function doSomething() {
var canvas = document.getElementById("can");
var ctx = canvas.getContext('2d');
/*
another scripts...
*/
}
window.addEventListener('onload', doSomething, false);
There are two things.
First, you don't need .innerHTML as other answers stated.
Second, you either have to run you script at the window load event like so:
window.addEventListener('load', function () {
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
ctx.fillStyle = ("green");
ctx.fillRect(0, 0, 300, 200);
});
Or you should load the javascript after the canvas tag.

canvas is not merging and resulting in showing only background image

I have create 2 canvas, load two differnt image and I want to merge both canvas and then display it as image in <div id="test"></div> tag.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas to image</title>
</head>
<body>
<div>
<canvas id="card_canvas" width="800" height="500"></canvas>
<canvas id="card_canvas2" width="800" height="500"></canvas>
</div>
<div id="test"></div>
<button onclick="canvasToImage()">canvas to image</button>
<script>
var img1 = new Image();
img1.src = "images/img1.jpg";
var cuimg;
function canvasToImage(){
var canvass1 = document.getElementById("card_canvas");
var canvass2 = document.getElementById("card_canvas2");
var ctx1 = canvass1.getContext('2d');
var ctx2 = canvass2.getContext('2d');
ctx1.drawImage(img1, 0, 0);
cuimg = new Image();
cuimg.onload = function(){
ctx2.drawImage(cuimg, 7, 92);
}
cuimg.src = "images/img2.jpg";
ctx1.drawImage(canvass2, 0, 0);
var imgdata = canvass1.toDataURL('image/png');
var mergeimg = document.createElement("img");
mergeimg.src = imgdata;
document.getElementById("test").appendChild(mergeimg);
}
</script>
</body>
</html>
Here is img1.jpg:
Here is img2.jpg:
This code ends up in displaying only background image:
I am expecting:
This can be achieve by simply setting following style on canvas2:
<canvas id="card_canvas2" style="position:absolute; left:0px; top:0px;"></canvas>
https://jsfiddle.net/jkjqd7gz/
I've been fiddling with your code a bit, and I think I've figured out the issue. javascript has a funny execution order at times that most people aren't aware of. Your onload lambda function is causing some of the issues your experiencing. Basically, you need to move your ctx1.drawImage(canvass2, 0, 0); line inside your lambda function just after ctx2.drawImage(cuimg, 7, 92); To understand what I mean open your code and hit the canvas to image button twice. The first time populates both canvasses, the second time puts the contents of canvass2 onto canvass1. I could probably explain exactly what's happening in terms of order of execution, but the explanation involves some difficult to understand concepts regarding parallelism, swap buffers, and race conditions.
To put it in a nutshell, whatever function you call ctx2.drawImage in, you need to then follow it with ctx1.drawImage. Honestly though, the best way to make composite images is to create a sprite class that stores an image, its postion, and layer information if desired. Then use a dynamic array to store the sprites. Always clear the canvas every time before you draw on it and loop through the contents of your arrays drawing each sprite in layer order on its respective canvass. Finally, I would use one set of functions to populate the canvas and a second to merge them.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas to image</title>
</head>
<body>
<div>
<canvas id="card_canvas" width="800" height="500"></canvas>
<canvas id="card_canvas2" width="800" height="500"></canvas>
</div>
<div id="test"></div>
<button onclick="popCanvas()">Populate Canvasses</button>
<button onclick="canvasToImage()">Canvas Combine</button>
<script>
var img1 = new Image();
img1.src = "images/img1.jpg";
var cuimg = new Image();
var canvass1 = document.getElementById("card_canvas");
var canvass2 = document.getElementById("card_canvas2");
function popCanvas(){
var ctx1 = canvass1.getContext('2d');
var ctx2 = canvass2.getContext('2d');
ctx1.clear()
ctx2.clear()
ctx1.drawImage(img1, 0, 0);
cuimg.onload = function(){
ctx2.drawImage(cuimg, 7, 92);
}
cuimg.src = "images/img2.jpg";
}
function canvasToImage(){
var ctx1 = canvass1.getContext('2d');
var ctx2 = canvass2.getContext('2d');
ctx1.drawImage(canvass2, 0, 0);
var imgdata = canvass1.toDataURL('image/png');
var mergeimg = document.createElement("img");
mergeimg.src = imgdata;
document.getElementById("test").appendChild(mergeimg);
}
</script>
</body>
</html>

Why does my HTML and JS not work?

I can't get this to work on my public webpage. I've made sure all permissions on files are correct, but when I go to the site, it just shows a blank page. It's supposed to have a matrix-like effect. I edited it through Codepen.io, but when I transfer it over to actual files and upload them, nothing works.
HTML:
<html><head>
<script src="(link the js file attached that is in the directory of my webpage)" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<meta charset="utf-8">
<title>Matrix</title>
</head>
<body>
<div align="center">
<canvas id="canvas" width="500" height="500">
</canvas><br/><br/>
</div>
</body>
</html>
JavaScript:
//this is my matrix.js file
$(document).ready(function(){
var s=window.screen;
var width = canvas.width=s.width;
var height = canvas.height;
var inLink = false;
var yPositions = Array(300).join(0).split('');
var context=canvas.getContext('2d');
var draw = function () {
context.fillStyle='rgba(0,0,0,.05)';
context.fillRect(0,0,width,height);
context.fillStyle='#0F0';
canvas.addEventListener("click", on_click, false);
canvas.addEventListener("mousemove", on_mousemove, false);
context.fillText(linkText,10,50);
context.font = '12pt Georgia';
yPositions.map(function(y, index){
text = String.fromCharCode(1e3+Math.random()*33);//determines characters randomly from this specific font
x = (index * 10)+10;
canvas.getContext('2d').fillText(text, x, y);
if(y > 100 + Math.random()*1e4)
{
yPositions[index]=0;
}
else
{
yPositions[index] = y + 10;
}
});
};
RunMatrix();
function RunMatrix()
{
if(typeof Game_Interval != "undefined") clearInterval(Game_Interval);
Game_Interval = setInterval(draw, 33);
}
})
You have to include your javascript files after the libraries they depend upon
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
type="text/javascript"></script>
<script src="(link the js file attached that is in the directory of my webpage)" type="text/javascript"></script>
Also, consider using a newer version of jQuery
try adding...
var canvas = document.getElementById('canvas');
at the start of your $(document).ready function...
$(document).ready(function(){
var canvas = document.getElementById('canvas');
....
basically you are referencing 'canvas', which doesn't appear to exist yet..
also make sure you're including jquery before any libraries or scripts that attempt to use it!

Adding a simple image in easeljs

This is my htmlcode:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="http://code.createjs.com/easeljs-0.7.0.min.js"></script>
<script src="Doge.js"></script>
</head>
<body bgcolor="#C7C7C7" onload="Start();">
<canvas id="DogeCanvas" width="480" height="320"></canvas>
</body>
</html>
And this is my Doge.js code:
function Start() {
var stage = new createjs.Stage("DogeCanvas");
var doge = new Image();
doge.src = "images/doge.jpg"
var bitmap = new createjs.Bitmap(doge);
stage.addChild(bitmap);
stage.update();
}
Why it doesn't show anything on the screen?
What is wrong?
The image is not loaded when the stage is updated. I posted an answer here:
ยป easeljs not showing bitmap
You can add a Ticker to the stage to constantly update it (which most applications do, since there is other things changing over time)
Listen for the onload of the image, and update the stage again
Preload the image with something like PreloadJS before you draw it to the stage.
As stated above you cannot draw your image until you have loaded it. Try this:
<!DOCTYPE HTML>
<html>
<title>Easel Test</title>
<head>
<script src="https://code.createjs.com/easeljs-0.8.0.min.js"></script>
<script>
var stage;
function init() {
stage = new createjs.Stage("myCanvas");
var image = new Image();
image.src = "path/image";
image.onload = handleImageLoad;
}
function handleImageLoad(event) {
var image = event.target;
var bitmap = new createjs.Bitmap(image);
stage.addChild(bitmap);
stage.update();
}
</script>
</head>
<body onload="init();">
<canvas id="myCanvas" width="960" height="580"></canvas>
</body>
</html>

Canvas toDataURL doesn't return whole URL on first try

I've got some code which takes a drawing made on in SVG with Raphael (a 400x400 image loaded into the SVG with Raphael), converts it to a canvas with canvg, and should then take canvas.toDataURL and make it an image. All of this should happen when a button is pushed. The first two steps work, but the third is glitchy. The first time I press the button, a 300x150 blank image is placed in the final div instead of the 400x400 image. If I press the button again, the image shows up fine (correct size and everything). I've tried to use both img.onload and the jquery version $(img).load but neither seems to keep the problem from happening. Therefore, I feel like it's an issue with the canvas having not been drawn completely yet but I can't prove that and I can't seem to make the code wait until it has been drawn. Below is all the code. I tried to make it a fiddle but I kept getting security errors with the image.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/raphael.js"></script>
<script type="text/javascript" src="scripts/excanvas.compiled.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var nowX, nowY, R = Raphael("svg_drawing", 400, 400);
$($("svg").get(0)).attr("xmlns:xlink", "http://www.w3.org/1999/xlink");
var templ = R.image("images/band_clutch.jpg", 0, 0, 400, 400);
});
function toImg(){
var svg = $("#svg_drawing").html().replace(/>\s+/g, ">").replace(/\s+</g, "<");
var canvas = $("#canvas")[0];
canvg(canvas, svg);
var imgData = canvas.toDataURL('image/jpg');
var img = new Image();
$(img).load(function(){
$("#drawing_area").html("");
$(img).appendTo("#drawing_area");
});
img.src = imgData;
}
</script>
<title>Sandbox</title>
</head>
<body style="margin: 0; width:3000px">
<div id="svg_drawing" style="background-color:white;display:inline-block;height:400px;width:400px;border:1px solid black;"></div>
<canvas id="canvas" style="display:inline-block;height:400px;width:400px;border:1px solid red;"></canvas>
<div id="drawing_area" style="background-color:white;display:inline-block;height:400px;width:400px;border:1px solid black;"></div>
<button onclick="toImg()" style="display:inline-block;vertical-align:top;">Do it</button>
</body>
</html>
It sounds like the canvas area is staying at the default 350 x 150. Try setting
canvas.width = canvas.height = 400;
before drawing (keep the inline CSS as-is).
To fix the actual rendering issue, you need to tell the canvg method to do the toDataURI stuff asyncronously, once the rendering has been complete:
function toImg(){
var svg = $("#svg_drawing").html().replace(/>\s+/g, ">").replace(/\s+</g, "<");
var canvas = $("#canvas")[0];
canvg(canvas, svg, {
renderCallback : function(){
var imgData = canvas.toDataURL('image/jpg');
var img = new Image();
$(img).load(function(){
$("#drawing_area").html("");
$(img).appendTo("#drawing_area");
});
img.src = imgData;
}
});
}

Categories

Resources