Tag Archives: javascript

SVG to Canvas (good trick)

Awhile back, I wrote some collision detection code that blitted existing interactive SVG to Canvas and then used the pixel data to figure out various aspects of the relationships between arbitrary SVG nodeTypes. A really simple trick I used can be seen in this pen:

The trick is to load the svg data into an image as a datauri. There are other tricks like this - one of which is using an svg `foreignObject` to blit html to canvas:


There were some browser issues at the time with this. The main one being IE 10/11 didn’t really work (tainted canvas if I recall correctly). The `foreignObject` trick didn’t work with image xlink:hrefs in safari at the time… (weirdly if you opened the dev tools it would start to work) anyway…

I ended up forking canvg for various cases. canvg is really cool… just a note, a coworker of mine went in at some point and optimized it like crazy and improved the perf a good deal by “drying things up”. Maybe I’ll suggest that he submit his optimizations at some point.

Posted in Graphics, html5, javascript, misc, pixel manipulation, svg | Also tagged , , , , , | Leave a comment

Input Field with LocalStorage Predictions

This is a quick example showing how to give an input field “memory”. After you type something once and hit return it will be stored in `localStorage`. String values are ranked based on how often they are selected/entered. I know people don’t like jQuery these days, seems this pen is from a time when I still used it.

There’s definitely room for improvement here - but the key features are covered.

Posted in html5, javascript | Also tagged , | Leave a comment

Quick line in HTML and JavaScript

Usually if you want to draw lines in HTML you use canvas or SVG. Awhile back I wondered how I might do it without those. This is really just a proof of concept speed coded answer to that question:

This works by using a div with a border, rotating it and scaling it as needed so it fits between two arbitrary points.

This could be abstracted a bit more, but it works pretty well. I usually choose `setInterval` over `requestAnimationFrame` when prototyping - because I like to easily be able to change the speed of
framebased things like this. If I were to try and make this code more dynamic, I would probably switch out to `requestAnimationFrame`.

If you try and connect two lines together - you’ll notice some inaccuracy - a good argument for using SVG or canvas over something like this. That said, if you are connecting two elements using a single line, this inaccuracy would become irrelevant.

Posted in Graphics, Math, html5, javascript, misc, motion | Also tagged , | Leave a comment

Color Breeder (aka Features)

Choose two colors to breed them and create 5 new colors:

This is a speed coded pen from awhile back - the features object is interesting - it allows two objects to be bred together. In this case two colors. I could see this is as part of some advanced/abstract colorpicker that allows the user to home in on a color.

Posted in Graphics, Object, html5, javascript, misc | Also tagged , | Leave a comment

3d Point to 2d Point (Easy Mini 3d Engine)

Many years ago when I had just started programming I found this absolute gem by Andries Odendaal.

modern es6 version

let rotX = 0, rotY = 0,
    perspective = 500, 
    currX, currY;
// learned something like this at Andries Odendaal's www.wireframe.co.za 
function point3d(x, y, z) {
    let cosX = Math.cos(rotX),
        cosY = Math.cos(rotY),
        sinX = Math.sin(rotX),
        sinY = Math.sin(rotY),
        posX, posY, posZ;
    posZ = z * cosX - x * sinX,
    posX = z * sinX + x * cosX,
    posY = y * cosY - posZ * sinY,
    posZ = y * sinY + posZ * cosY;
    depth = 1 / (posZ / perspective + 1);
    currX = posX * depth;
    currY = posY * depth;
    return [ currX, currY, depth ];

Here’s is an example of it in action:

I’ve used this code many many times, it’s just easy to throw into any language and instantly get 3d points rendered in 2d. Here is a short video of a Java applet from 2003 called “Catch Env” that made use of it:

Here is the source code for that ^^

You’ll notice in that source, that I nested the equation to allow for local and global transformations. It was around that time that I learned the ins and outs of real 2D and 3D matrix transformation math… Ken Perlin’s classfiles from NYU were a real help when I was learning that stuff. I don’t think this was the exact file I was working with, but it was definitely on his site somewhere.

Before all that, during my junior year in college I created a 3d engine based off Odendaal’s code in Director (Lingo). Here is a video of some of the demos for it:

…and here is a strange screenshot from my personal website at the time:

Just an example of a powerful snippet and a gateway to learning matrix transformation math. When I first really dug in to html5 canvas - before WebGL was supported so widely - having this trick up my sleeve was great. As you can see in the below link, I used it more than a few times back then:

Daily canvas experiments:



Posted in 3D, Graphics, graphics algorithms, html5, javascript | Also tagged , , | Leave a comment

Dynamic Getter

Getters in ES6 are usually defined within a class like this:

  class RandomPoint {
    get x() {
      return Math.random();
    get y() {
      return Math.random();

In this case we use getters to make a random point:

  let pnt = new RandomPoint();
  console.log(pnt.x, pnt.y);
  // outputs something like 0.09403673512366306 0.2717692041118973

I found myself wanting to be able to dynamically define a getter. This can be done like this:

let rand = function() { return Math.random(); };
Object.defineProperties(someObj, { ['x']: { get: rand });

This is really all just sugar, but still fun stuff…

Posted in Uncategorized, javascript | Also tagged | Leave a comment

HTML5 Canvas Tutorial

If you haven’t tried the html5 canvas tag yet, I suggest you give it a try. It falls under the same category as ActionScript’s Graphics and BitmapData classes. It is however much much simpler. One great thing about it is it runs really fast on IOS5. Have a look at some of these demos to see what I mean: http://zreference.com/projects/graphics/

A few days ago I recorded this short video tutorial… it’s very simple, but it will get you started if you’ve never tried canvas before:

Posted in html5, javascript | Also tagged , , , | 2 Comments

Hide Browser Scrollbars

  1. /*
  2. This snippet is by Mels le Noble
  3. www.melslenoble.nl
  4. It will hide the browser scrollbars.
  5. */
  7. // see if we are testing locally
  8. if (stage.loaderInfo.url.split("/")[2])
  9. {
  10.  ExternalInterface.call("function(){document.body.style.overflow='hidden';document.html.style.overflow = 'hidden';}");
  11. }

This snippet by Mels le Noble will hide the browser scrollbars. The bulk of the snippet is the javascript inside the ExternalInterface.call() method. I like the trick that Mels uses to check if the swf is local.... snippet-worthy in itself.

Posted in UI | Also tagged , , , | Leave a comment

JS Sketch Experiment

  1. [SWF(width=950, height=600)]
  2. with (graphics) beginFill(0xefefef), drawRect(0,0,stage.stageWidth, stage.stageHeight);
  3. var btn:Sprite = Sprite(addChild(new Sprite()));
  4. with (btn.graphics) beginFill(0x666666), drawRect(0,0,100,20);
  5. with(btn)  x=320, y=430, buttonMode = true;
  6. btn.addEventListener(MouseEvent.ROLL_OVER, function():void{
  7.   with(btn.graphics) clear(), beginFill(0x222222), drawRect(0,0,100,20);
  8. });
  9. btn.addEventListener(MouseEvent.ROLL_OUT, function():void{
  10.   with(btn.graphics) clear(), beginFill(0x666666), drawRect(0,0,100,20);
  11. });
  12. btn.addEventListener(MouseEvent.CLICK, function():void{
  13.     var res:*= ExternalInterface.call("function(){ plot=[]; colors=[]; " + txt.text + " return {plot:plot, colors:colors};}");
  14.     render((res == null) ? {plot:[], colors:[]} : res);
  15. });
  17. var v:Shape = Shape(addChild(new Shape()));
  18. v.x = 700;
  19. v.y = 220;
  20. function render(obj:Object):void{
  21.     var plot:Array = obj.plot;
  22.     var colors:Array = obj.colors;
  23.     var leng:int = plot.length;
  24.     v.graphics.clear();
  25.     var inc:int = 0;
  26.     v.graphics.moveTo(plot[0], plot[1]);
  27.     for (var i:int = 2; i<leng; i+=2){
  28.         v.graphics.lineStyle(0,colors[inc++]);
  29.         v.graphics.lineTo(plot[i], plot[i + 1]);
  30.     }
  31. }
  34. var submit:TextField = TextField(btn.addChild(new TextField()));
  35. submit.defaultTextFormat = new TextFormat("_sans", 12);
  36. with(submit) textColor=0xFFFFFF, width=100, autoSize="center";
  37. with(submit) mouseEnabled = false,  text="submit";
  39. var txt:TextField = TextField(addChild(new TextField()));
  40. with(txt) x = y = 20, type = "input", multiline=true;
  41. with(txt) width = 400, height = 400, border = true, background = 0xFFFFFF;
  42. txt.defaultTextFormat = new TextFormat("Monaco", 12);
  43. txt.text = "enter text";
  44. txt.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
  45. function onDown(evt:MouseEvent):void{
  46.     txt.text = "";
  47.     txt.removeEventListener(MouseEvent.MOUSE_DOWN, onDown);
  48. }

This snippet is a mini code editor that allows the user to write javascript into a textfield - the javascript is then run using external interface. Optionally the javascript code can populate two arrays (plot and colors). If these arrays are populated flash, will render the data in each array using the Graphics class.

Have a look at the demo:

If you do something nice with this... post your javascript snippet as a comment and I'll add it to the JS Sketch page...

Posted in Graphics, Math, dynamic, external data, functions | Also tagged , , | Leave a comment

ActionScript Eval (well, not really)

  1. var txt:TextField = TextField(addChild(new TextField()));
  2. txt.autoSize = TextFieldAutoSize.LEFT;
  4. var myVar:Number = 100;
  5. // works as an expression parser
  6. txt.text = js("return (" + myVar + " * 2 + 10) / 2");
  7. txt.appendText("\n\n");
  9. // parses javascript
  10. txt.appendText(js("var a = []; for (var i = 0; i<10; i++){ a.push(i) } return a;"));
  12. function js( data:String ):*{
  13.    var res:*= ExternalInterface.call("function(){" + data + "}");
  14.    return (res == null) ? "null" : res;
  15. }

This one made my day - CAN'T believe I never thought of it before... haven't done any speed tests yet... but it shows how to use ExternalInterface.call to parse math expressions and javascript code. This will only work when the swf is shown in an html page of course... so if your in flash cmd+f12...

I got the idea from this code snippet... which actually has an error in it... the decode() function should not return void... I found that snippet thanks to this tweet by makc3d.

Posted in Math, external data, functions, misc, string manipulation, strings | Also tagged , | Leave a comment