How to get the canvas element by jquery? - javascript

Currently I'm play with the html5 canvas, the simple code is below:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="Scripts/jquery-2.0.3.min.js"></script>
<script>
$(function () {
//THIS WILL NOT WORK!
//var cv = $("#cv");
//THIS WORKS FINE.
var cv = document.getElementById("cv");
ct = cv.getContext("2d");
var mText = "hi";
var x = cv.width / 2;
var y = cv.height / 2;
ct.textAligh = "center";
ct.fillText(mText, x, y);
});
</script>
</head>
<body>
<div style="width:200px; height:200px; margin:0 auto; padding:5px;">
<canvas id="cv" width="200" height="200" style="border:2px solid black">
Your browser doesn't support html5! Please download a fitable browser.
</canvas>
</div>
</body>
</html>
The canvas element could only be picked by the method document.getElementById, but the jQuery method is not working. Is there a way to get the original html from the jquery object or am I miss using something?
Thanks in advance!

jQuery's $(<selector>) returns a collection of nodes (in fact it is "object masquerades as an array" as the doc says) so just use $('#cv').get(0) instead of document.getElementById("cv")

You need to use .get() following to get the actual DOM element:
var canvas = $("#cv").get(0);
Otherwise, you're getting the jQuery object when you only do $("#cv"), so methods such as getContext will not work.

using get()
http://api.jquery.com/get/
explore the jquery doc, it's very useful

Related

Javascript OOP question - Changing element properties

I am trying to understand why neither of the commented out scripts work. When I step through the code in the console they are both returning the correct variable values but neither of the commented out code changes the image size. I would think that either one of commented set of scripts would be the correct as opposed to the way that works. If someone could please help me with what I am not understanding it would be greatly appreciated. thanks
<!DOCTYPE html>
<html>
</head>
<body>
<img onmouseover = "increaseSize(this)" id="img2" width="400px" height="400px" src="20191128chichenitza.jpg" title="Chichenitza">
<script>
function increaseSize(y) {
var currWidth = y.clientWidth*1.50;
var currHeight = y.clientHeight*1.50;
y.width = currWidth;
y.height = currHeight;
/*document.getElementById("img2").style.width = currWidth;
document.getElementById("img2").style.height = currHeight;
or
y.style.width = currWidth;
y.style.height = currHeight;
*/
}
</script>
</body>
</html>
The value of .style.width must be set in the same way as you would in CSS. Therefore, y.style.width = currWidth + "px";

How can I include more than one Javascript file?

I want to use more Javascript files on one canvas, but I can't connect them. For example I want to write a Javascript file that contains all functions and an other Javascript file which is using them.
Show me a guide, how can I make this connection?
Thanks.
This is the first javascript file :
var canvas = null;
var ctx = null;
window.onload = function () {
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
line (100,100,300,300);
}
This is the secnond file:
function line (x1,y1,x2,y2) {
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
And this is my html file:
<!DOCTYPE html>
<html>
<head>
<title>Tutorialok</title>
<script type="text/javascript" src="CanvasElement.js"></script>
<script type="text/javascript" src="line.js"></script>
<style>
#myCanvas {
border: 1px solid #9C9898;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="800" height="600">
Sorry your browser Does not support canvas element!
</canvas>
</body>
</html>
The first file cant find the second files function.
Use namespacing via Objects. I don't recommend a pattern where all functions exist in one file, but this is an idea you could use. You MUST load file1.js before file2.js can do anything.
// file1.js
window.namespace = window.namespace || {};
window.namespace.fns = {
foo: function () {}
};
// file2.js
window.namespace.fns.foo();
jsFile 1
var f1 = function(){};
var f2 = function(){}
jsFile2
var s1 = f1();
var s2 = f2();
use this on the html page
<script src="path/jsFile1.js"></script>
<script src="path/jsFile2.js"></script>
If you're expecting the function to hoist, I don't believe that would work between script files since each one is evaluated independently. Switch the script tags around so line is in scope when CanvasElement.js loads.
Otherwise, the global namespace is shared between the linked scripts.

How to select element based on another already-existing selector?

I have the following code:
<html>
<head>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("jquery", 1);
</script>
<script type="text/javascript">
var rt, rt2;
window.onload = function () {
rt = $('#rt').contents().get(0);
rt.designMode = 'On';
}
</script>
</head>
<body>
<iframe id="rt" width="500" height="500"></iframe>
</body>
</html>
rt is currently selecting the whole iframe document. I want rt2 to select the body element inside the document element, which is what rt is selecting. I tried:
rt2 = jQuery(rt, "html");
rt2 = jQuery(rt2, "body");
But it didn't seem to work. How would it be possible?
According to the documentation, the context to search within should be supplied as the second parameter, not the first, so try this instead:
rt2 = jQuery("html", rt);
The context can be:
A DOM Element, Document, or jQuery to use as context
Internally, the context is implemented using the .find() method. So the above example is just a short hand of:
rt2 = jQuery(rt).find("html");
Use find:
var myFrame = $('#rt').contents();
var myvar = myFrame.find('body');
Try with:
rt2body = iframeElement.find("body");
Further reading on .find: http://api.jquery.com/find/

How can i return img.src by clicking on an image with javascript?

I am trying to create a function with javascript where a user upon clicking on an image can retrieve that images src as a URL. I am very new to javascript and my attempts so far at creating a function activated by "onclick" of an image are:
var showsrc = function(imageurl)
var img = new Image();
img.src = imageurl
return img.src
to call the results i have been trying to insert the image.src into my html using
document.getElementById("x").innerHTML=imageurl;
Im having very little success. Any help would be greatly appreciated. Thank you.
I tested this in IE9 and Chrome 17. Add an onclick handler to the body (or nearest container for all your images) and then monitor if the clicked element is an image. If so show the url.
http://jsfiddle.net/JbHdP/
var body = document.getElementsByTagName('body')[0];
body.onclick = function(e) {
if (e.srcElement.tagName == 'IMG') alert(e.srcElement.src);
};​
I think you want something like this: http://jsfiddle.net/dLAkL/
See code here:
HTML:
<div id="urldiv">KEINE URL</div>
<div>
<img src="http://www.scstattegg.at/images/netz-auge.jpg" onclick="picurl(this);">
<img src="http://www.pictokon.net/bilder/2007-06-g/sonnenhut-bestimmung-pflege-bilder.jpg.jpg" onclick="picurl(this);">
</div>​
JAVASCRIPT
picurl = function(imgtag) {
document.getElementById("urldiv").innerHTML = imgtag.getAttribute("src");
}​
Image tags do not have an 'innerHTML', since they're singleton tags - they cannot have any children. If your x id is the image tag itself, then:
alert(document.getElementById('x').src);
would spit out the src of the image.
Here's a naïve solution with just javascript (probably not cross-browser compatible):
<!doctype html>
<html>
<head>
<script>
function init() {
var images = document.getElementsByTagName('img');
for(var i = 0, len = images.length; i < len; i++) {
images[i].addEventListener('click', showImageSrc);
}
}
function showImageSrc(e) {
alert(e.target.src);
}
</script>
</head>
<body onload="init()">
<img src="http://placekitten.com/300/300">
</body>
</html>

Adding an img element to a div with javascript

I am trying to add an img to the placehere div using JavaScript, however I am having no luck. Can anyone give me a hand with my code?
<html>
<script type="text/javascript">
var elem = document.createElement("img");
elem.setAttribute("src", "images/hydrangeas.jpg");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild("elem");
</script>
<body>
<div id="placehere">
</div>
</body>
</html>
document.getElementById("placehere").appendChild(elem);
not
document.getElementById("placehere").appendChild("elem");
and use the below to set the source
elem.src = 'images/hydrangeas.jpg';
It should be:
document.getElementById("placehere").appendChild(elem);
And place your div before your javascript, because if you don't, the javascript executes before the div exists. Or wait for it to load. So your code looks like this:
window.onload = function() {
var elem = document.createElement("img");
elem.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild(elem);
}
<div id="placehere"></div>
To prove my point, see this with the onload and this without the onload. Fire up the console and you'll find an error stating that the div doesn't exist or cannot find appendChild method of null.
function image()
{
//dynamically add an image and set its attribute
var img=document.createElement("img");
img.src="p1.jpg"
img.id="picture"
var foo = document.getElementById("fooBar");
foo.appendChild(img);
}
<span id="fooBar"> </span>
The following solution seems to be a much shorter version for that:
<div id="imageDiv"></div>
In Javascript:
document.getElementById('imageDiv').innerHTML = '<img width="100" height="100" src="images/hydrangeas.jpg">';
In case anyone is wondering how to do it with JQuery:
$("<img height='200' width='200' alt='testImage' src='https://avatars.githubusercontent.com/u/47340995?v=4'> </img>").appendTo("#container");
Ref: https://api.jquery.com/jQuery/#jQuery2

Categories