Drawing HTML to a Canvas - javascript

With the advent of the new HTML5 Canvas, I was wondering if it's possible to draw a HTML section onto the canvas?
The idea is to take a piece of existing HTML code (from the same page, or defined elsewhere) and turn it into graphics.
Something like:
htContext.drawElement(document.getObjectByID("someObj"),0,0);

Firefox has proprietary method drawWindow. With it you can draw the whole document on the canvas. But only in Firefox unfortunately. And also due to security issues you need permissions from the user to do it. So it's suitable only for some kind of internal project.
Here is the sample test page:
<!DOCTYPE html>
<html>
<head>
<title>drawWindow</title>
<script>
window.onload = function(){
netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
document.getElementById('canvas').getContext('2d').drawWindow(window, 0, 0, 100, 200, "rgb(255,255,255)");
}
</script>
</head>
<body>
<h1>Test</h1>
<canvas id="canvas"></canvas>
</body>
</html>

Related

Run time compile order

I'm coding in Javascript and I came to an example which I figure was strange.
Example:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,20,0,2*Math.PI);
ctx.stroke();
</script>
</body>
</html>
The above example works and outputs a circle.
However, when I try to copy the exact codes of the script onto a javascript.js file, the circle ceases to exist. Why is that the case?
<!DOCTYPE html>
<html>
<head>
<script src="javascriptFile.js"></script>
</head>
<body>
<canvas id="myCanvas"></canvas>
</body>
</html>
I thought the order of precedence would be that the web browser publishes the html code, and then constructs the DOM which I figure javascript code would run right after the html objects are created. I tried putting a function createShape() inside the canvas and then insert the rest of the codes in function createShape(){} of the javascriptFile.js file but didn't work either.
Would I have to always put the javascript codes in the html body for all canvas objects?
I thought the order of precedence would be that the web browser publishes the html code, and then constructs the DOM which I figure javascript code would run right after the html objects are created.
That is incorrect. Generally, if your JavaScript code appears in the source before the elements it is trying to access (and is not explicitly marked as defered), it will be executed before the browser continues to parse the page.
Embed the script at the bottom of the body and you should be fine:
<!DOCTYPE html>
<html>
<head></head>
<body>
<canvas id="myCanvas"></canvas>
<script src="javascriptFile.js"></script>
</body>
</html>

How do you setup processingJS on html?

How do you run a processingJS script on an html page? Could someone send me a test .html and any auxiliary code files for me to get an idea?
Let's say I wanted to run this rectangle:
rect(50,50,50,50);
To add to Kevin's answer, if you want to use the Processing.js library with javascript rather than pde (java) code this may make it a little easier to dive in.
*Note that some javascript folks may cringe at the use of with(obj){code}, but I give this as an example to unclutter the code and make it less verbose. Use your own judgement depending on the circumstances.
Also make sure that the processing library is in the same folder as your file with the below code and the name of the file is correct in the below code.
Enjoy! :)
<html>
<head>
</head>
<body>
<canvas id="output-canvas"></canvas>
<script src="processing.1.4.8.js"></script>
<script> ( function () {
new Processing ( document.getElementById ( "output-canvas"), sketch );
function sketch ( pjs ) {
// some initilization if you prefer
// set the canvas size
pjs.size ( 800, 600 );
// ( 0, 0, 0, 0 ) - if you want a transparent sketch over some backdrop
pjs.background ( 255, 255, 255, 255 );
// make the ugly pjs go away
with ( pjs ) {
// red stroke
stroke ( 255, 0, 0 );
// thick border
strokeWeight ( 5 );
// yellow fill
fill ( 255, 240, 0 );
// draw a rectangle
rect ( 50, 50, 300, 200 );
}
}
} ) (); </script>
</body>
</html>
Everything you want to know is on this page: JavaScript Quick Start | Processing.js
But basically, you need to do create an html file that loads the Processing.js library, then write Processing.js code and load the .pde file into a canvas tag on that page. It looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Hello Web - Processing.js Test</title>
<script src="processing-1.3.6.min.js"></script>
</head>
<body>
<h1>Processing.js Test</h1>
<p>This is my first Processing.js web-based sketch:</p>
<canvas data-processing-sources="hello-web.pde"></canvas>
</body>
</html>
The easiest way to do that is to use JavaScript mode from the Processing editor (you might have to use version 2.2.1), then click run. You can then view the files created by the editor (go to view > sketch folder) to get a better idea of what's going on under the hood.

How to create textbox in canvas

I wanted to create text box inside the canvas.
HTML
<canvas id="canvas" width="200" height="50"></canvas>
JavaScript
var input = new CanvasInput({
canvas: document.getElementById('canvas')
});
when I run the file HTML not have anything.
You just simply missed the libraries CanvasInput.min.js simply download from the here and add to your code.
Sample Code:
<html>
<title>sample</title>
<head>
<script src="CanvasInput.min.js"></script>
</head>
<body>
<canvas id="canvas" width="200" height="50"></canvas>
<script>
var input = new CanvasInput({
canvas: document.getElementById('canvas')
});
</script>
</body>
</html>
You cannot simply render a standard HTML input field inside a canvas, if that's what you wanted to achieve.
It looks like you were trying to utilize code from this developer page. But it seems you overlooked that there is a whole lot more Javascript required to simulate an input field as a canvas graphic element. Check out this Git repository to see the whole code.
I made a CodePen showing how to put a text input inside a canvas with this technique. For a quick demo add this script tag to your HTML code (you may want to host the code yourself later):
<script type="text/javascript" src="http://goldfirestudios.com/proj/canvasinput/CanvasInput.min.js?v=1.2.0"></script>

Can't run very first tracking.js example on Chrome

I'm trying to get familiar with tracking.js, but when I try to run the very same example given on the project's page (http://trackingjs.com/docs.html#introduction), nothing happens.
Google-chrome doesn't even shows the prompt asking if I want to allow the page to access to my webcam. The same thing happens for Firefox.
I have already ran the other examples from the tracking.js-master/ package, and the only one that fails is the one described on the tutorial, which I've added.
Below is the code which I copied and pasted from the tracking.js intro page to my first_tracking.html file.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>tracking.js - first tracking</title>
<script src="../build/tracking-min.js"></script>
</head>
<body>
<p>This shows in the browser</p>
<video id="myVideo" width="400" height="300" preload autoplay loop muted></video>
<script>
var colors = new tracking.ColorTracker(['magenta', 'cyan', 'yellow']);
colors.on('track', function(event) {
if (event.data.length === 0) {
// No colors were detected in this frame.
} else {
event.data.forEach(function(rect) {
console.log(rect.x, rect.y, rect.height, rect.width, rect.color);
});
}
});
tracking.track('#myVideo', colors);
</script>
</body>
</html>
Has anyone tried and succeeded in running the introduction examples listed on the tracking.js page and have any pointers?
Research: Most of the stuff found on a google search relate to Google Analytics, Node.js and other JS frameworks. I also found some people suggesting setting the preload option to auto, resulting in preload="auto", but it didn't work.
I was able to get the example working with the webcam. Here's how.
First, Go into to root tracking.js directory and start a simple server. If you have python installed, try running python -m SimpleHTTPServer, then visit http://localhost:8000/examples/first_tracking.html to see your example, assuming your file is located in the examples directory of the unzipped file. This is important. If you just open the file in your browser, you will get an error: Canvas tainted by cross-origin data
Save the following code to first_tracking.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>tracking.js - first tracking</title>
<script src="../build/tracking-min.js"></script>
</head>
<body>
<video id="myVideo" width="400" height="300" preload autoplay loop muted></video>
<script>
var colors = new tracking.ColorTracker(['magenta', 'cyan', 'yellow']);
colors.on('track', function(event) {
if (event.data.length === 0) {
// No colors were detected in this frame.
} else {
event.data.forEach(function(rect) {
console.log(rect.x, rect.y, rect.height, rect.width, rect.color);
});
}
});
window.onload = function() {
// note here that 'camera' is set to true, I believe this tells tracking.js to use
// the webcam.
tracking.track('#myVideo', colors, {camera: true});
}
</script>
</body>
</html>
Make sure your server is still running, then visit http://localhost:8000/examples/first_tracking.html and inspect the console. You should see output like the following
260 47 37 47 "cyan" first_tracking.html:18
I recently ran into this problem myself and the issue for me was a missing parameter to the tracking.track() call...
The example online shows this:
tracking.track('#myVideo', colors);
When it should be this:
tracking.track('#myVideo', colors, { camera: true });
Technically Julia's post includes this param so I'm ok with that as the accepted answer, but just in case someone else runs into this problem, this is what fixed it for me. With the camera flag, I was able to run the example without waiting for dom load as well, if that matters for anyone else.
{ camera: true } is missing from the example code. As previous answers mention, include tracking.track('#myVideo', colors, { camera: true });

Canvas toDataURL() giving blank image

I'm a complete beginner to JS and I'm just playing around with HTML5. While experimenting, I came across this issue. I have something like this:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function graph() {
// ...stuff that draws to canvas, verified "working"...
var downloadLink = document.getElementById("myCanvas").toDataURL();
$("#dlLink").attr("href", downloadLink);
}
$(window).load(function() {
graph();
});
</script>
</head>
<body>
<div class="container">
<h1 style = ";padding-bottom:30px;">Tool</h1>
<canvas id="myCanvas" width="400" height="400"></canvas>
Download
</div>
</body>
</html>
When I click the download link with the base64 encoding, I get a blank image. Can anyone bring to light why this is happening? It seems like the link is generated before the canvas has anything on it, but I can't be sure.
Instead, try this:
$("#dlLink").click(function(){
var win=window.open();
win.document.write("<img src='"+document.getElementById("myCanvas").toDataURL()+"'/>");
});
Try passing toDataURL a content type like "image/png" or "image/jpeg". (canvas.toDataURL("image/png"));

Categories

Resources