Selecting individual letters in .print with Raphael 2.1 - javascript

I tried to do what this Raphael tutorial [ http://www.html5rocks.com/en/tutorials/raphael/intro/ ] does and select individual letters from a string printed with .print, but no joy
I have generated the font with cufon, and replaced Cufon.registerFont with Raphael.registerFont
var paper = Raphael( '#div', 500, 500 ),
label = paper.print( xCenter, yCenter, 'blah', paper.getFont("CelliniProMedium"), 54 );
label[1].attr( 'fill', 'red');
causes an error because label is just a path not an array of paths.
What gives?
thanks in advance

Yeah, this is definitely a change in behavior between 1.4 and 2.0 -- and it's a bit of functionality that came in handy in more than one situation.
On the other hand, replicating the array result functionality is easy to do by extending Raphael 2.0...
Raphael.fn.printArray = function printArray( x, y, string, font, size, letter_spacing, line_height )
{
var result = [];
var cx = x, cy = y;
size = size || 16;
letter_spacing = letter_spacing || 0.2;
line_height = line_height || 1.5;
for ( var i = 0; i < string.length; i++ )
{
if ( string[i] == " " )
{
cx += size;
continue;
}
else if ( string[i] == "\n" )
{
cx = x;
cy += size * line_height;
continue;
}
var glyph = this.print( 0, 0, string[i], font, size ).attr( { opacity: 0 } );
var glyphBox = glyph.getBBox();
glyph.attr( { transform: "T" + cx + "," + cy, opacity: 1 } );
cx += glyphBox.width + ( size * letter_spacing );
result.push( glyph );
}
return result;
}
This isn't perfect code, but with a little refinement it could easily fill the gap.

so it looks like it's either a bug or a feature with 2.1 - I got 1.4 from GitHub and it works as expected. Leaving question open for a short while in case anyone can shed any more lights on this, as I think it may be useful to others.

Related

Find Hex Colors and X,Y in Images

I am trying to find all the hex colors in an image and if possible, circle or highlight the X, Y position of where the hex color(s) are. My current code is attempting to find all colors and almost crashes my browser and my attempt to find the X,Y coordinates of each image isn't going good either.
I have two functions doing different things, it's what I have tried to work with to give an example of what has been attempted... Any help would be great!
Any assistance would be amazing!
<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<img id="origImage" width="220" height="277" src="loggraph.PNG">
<script>
function getPixel(imgData, index) {
var i = index*4, d = imgData.data;
return [d[i],d[i+1],d[i+2],d[i+3]] // [R,G,B,A]
}
function getPixelXY(imgData, x, y) {
return getPixel(imgData, y*imgData.width+x);
}
function goCheck() {
var cvs = document.createElement('canvas'),
img = document.getElementsByTagName("img")[0];
cvs.width = img.width; cvs.height = img.height;
var ctx = cvs.getContext("2d");
ctx.drawImage(img,0,0,cvs.width,cvs.height);
var idt = ctx.getImageData(0,0,cvs.width,cvs.height);
console.log(getPixel(idt, 852)); // returns array [red, green, blue, alpha]
console.log(getPixelXY(idt,1,1)); // same pixel using x,y
}
function getColors(){
var canvas = document.getElementById("myCanvas");
var devices = canvas.getContext("2d");
var imageData = devices.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data;
// iterate over all pixels
for(var i = 0, n = data.length; i < n; i += 4) {
var r = data[i];
var g = data[i + 1];
var b = data[i + 2];
var rgb = "("+r+","+g+","+b+")";
var incoming = i*4, d = imageData.data;
var bah = [d[incoming],d[incoming+1],d[incoming+2],d[incoming+3]];
$('#list').append("<li>"+rgb+"</li>");
colorList.push(rgb);
}
$('#list').append("<li>"+[d[incoming],d[incoming+1],d[incoming+2],d[incoming+3]]+"</li>");
}
}
Must check all pixels
To find a pixel that matches a color will require, in the worst case (pixel of that color not in image), that you step over every pixel in the image.
How not to do it
Converting every pixel to a DOM string is about the worst way to do it, as DOM string use a lot of memory and CPU overhead, especially if instantiated using jQuery (which has its own additional baggage)
Hex color to array
To find the pixel you need only check each pixels color data against the HEX value. You convert the hex value to an array of 3 Bytes.
The following function will convert from CSS Hex formats "#HHH" "#HHHH", "#HHHHHH" and "#HHHHHHHH" ignoring the alpha part if included, to an array of integers 0-255
const hex2RGB = h => {
if(h.length === 4 || h.length === 5) {
return [parseInt(h[1] + h[1], 16), parseInt(h[2] + h[2], 16), parseInt(h[3] + h[3], 16)];
}
return [parseInt(h[1] + h[2], 16), parseInt(h[3] + h[4], 16), parseInt(h[5] + h[6], 16)];
}
Finding the pixel
I do not know how you plan to use such a feature so the example below is a general purpose method that will help and can be modified as needed
It will always find a pixel if you let it even if there is no perfect match. It does this by finding the closest color to the color you are looking for.
The reason that of finds the closest match is that when you draw an image onto a 2D canvas the pixel values are modified slightly if the image has transparent pixels (pre-multiplied alpha)
The function finds the pixel by measuring the spacial distance between the pixel and the hex color (simple geometry Pythagoras). The closest color is the one that is the smallest distance.
It will return the object
{
x, // the x coordinate of the match
y, // the y coordinate of the match
distance, // how closely the color matches the requested color.
// 0 means a perfect match
// to 441 completely different eg black and white
// value is floored to an integer value
}
If the image is tainted (cross origin, local device storage), or you pass something that can not be converted to pixels the function will return undefined
The function keeps a canvas that it uses to get pixel data as it assumes that it will be use many times. If the image is tainted it will catch the error (add a warning to the console), cleanup the tainted canvas and be ready for another image.
Usage
To use the function add it to your code base, it will setup automatically.
Get an image and a hex value and call the function with the image, CSS hex color, and optionally the threshold distance for the color match.
Eg find exact match for #FF0000
const result = findPixel(origImage, "#FF0000", 0); // find exact match for red
if (result) { // only if found
console.log("Found color #FF0000 at pixel " + result.x + ", " + result.y);
} else {
console.log("The color #FF0000 is not in the image");
}
or find color close to
const result = findPixel(origImage, "#FF0000", 20); // find a match for red
// within 20 units.
// A unit is 1 of 256
if (result) { // only if found
console.log("Found closest color within " + result.distance + "units of #FF0000 at pixel " + result.x + ", " + result.y);
}
or find closest
// find the closest, no threshold ensures a result
const result = findPixel(origImage, "#FF0000");
console.log("Found closest color within " + result.distance + "units of #FF0000 at pixel " + result.x + ", " + result.y);
Code
The function is as follows.
const findPixel = (() => {
var can, ctx;
function createCanvas(w, h) {
if (can === undefined){
can = document.createElement("canvas");
ctx = can.getContext("2d");
}
can.width = w;
can.height = h;
}
function getPixels(img) {
const w = img.naturalWidth || img.width, h = img.naturalHeight || img.height;
createCanvas(w, h);
ctx.drawImage(img, 0, 0);
try {
const imgData = ctx.getImageData(0, 0, w, h);
can.width = can.height = 1; // make canvas as small as possible so it wont
// hold memory. Leave in place to avoid instantiation overheads
return imgData;
} catch(e) {
console.warn("Image is un-trusted and pixel access is blocked");
ctx = can = undefined; // canvas and context can no longer be used so dump them
}
return {width: 0, height: 0, data: []}; // return empty pixel data
}
const hex2RGB = h => { // Hex color to array of 3 values
if(h.length === 4 || h.length === 5) {
return [parseInt(h[1] + h[1], 16), parseInt(h[2] + h[2], 16), parseInt(h[3] + h[3], 16)];
}
return [parseInt(h[1] + h[2], 16), parseInt(h[3] + h[4], 16), parseInt(h[5] + h[6], 16)];
}
const idx2Coord = (idx, w) => ({x: idx % w, y: idx / w | 0});
return function (img, hex, minDist = Infinity) {
const [r, g, b] = hex2RGB(hex);
const {width, height, data} = getPixels(img);
var idx = 0, found;
while (idx < data.length) {
const R = data[idx] - r;
const G = data[idx + 1] - g;
const B = data[idx + 2] - b;
const d = R * R + G * G + B * B;
if (d === 0) { // found exact match
return {...idx2Coord(idx / 4, width), distance: 0};
}
if (d < minDist) {
minDist = d;
found = idx;
}
idx += 4;
}
return found ? {...idx2Coord(found / 4, width), distance: minDist ** 0.5 | 0 } : undefined;
}
})();
This function has been tested and works as described above.
Note Going by the code in the your question the alpha value of the image and CSS hex color is ignored.
Note that if you intend to find many colors from the same image this function is not the best suited for you needs. If this is the case let me know in the comment and I can make changes or instruct you how to optimism the code for such uses.
Note It is not well suited for single use only. However if this is the case change the line const findPixel = (() => { to var findPixel = (() => { and after you have used it remove the reference findpixel = undefined; and JS will clean up any resources it holds.
Note If you also want to get the actual color of the closest found color that is trivial to add as well. Ask in the comments.
Note It is reasonably quick (you will be hard pressed to get a quicker result) but be warned that for very large images 4K and above it may take a bit, and on very low end devices it may cause a out of memory error. If this is a problem then another solution is possible but is far slower.

How to get a css value using jQuery [duplicate]

I have CSS style for a layer:
.element {
-webkit-transform: rotate(7.5deg);
-moz-transform: rotate(7.5deg);
-ms-transform: rotate(7.5deg);
-o-transform: rotate(7.5deg);
transform: rotate(7.5deg);
}
Is there a way to get curent rotation value through jQuery?
I tried this
$('.element').css("-moz-transform")
The result is matrix(0.991445, 0.130526, -0.130526, 0.991445, 0px, 0px) which doesn't tell me a lot. What I'm looking to get is 7.5.
Here's my solution using jQuery.
This returns a numerical value corresponding to the rotation applied to any HTML element.
function getRotationDegrees(obj) {
var matrix = obj.css("-webkit-transform") ||
obj.css("-moz-transform") ||
obj.css("-ms-transform") ||
obj.css("-o-transform") ||
obj.css("transform");
if(matrix !== 'none') {
var values = matrix.split('(')[1].split(')')[0].split(',');
var a = values[0];
var b = values[1];
var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
} else { var angle = 0; }
return (angle < 0) ? angle + 360 : angle;
}
angle1 = getRotationDegrees($('#myDiv'));
angle2 = getRotationDegrees($('.mySpan a:last-child'));
etc...
I've found a bug/features in the Twist's code: the function return negative angles.
So I've add a simple line of code before returning the angle:
if(angle < 0) angle +=360;
Than the results will be:
function getRotationDegrees(obj) {
var matrix = obj.css("-webkit-transform") ||
obj.css("-moz-transform") ||
obj.css("-ms-transform") ||
obj.css("-o-transform") ||
obj.css("transform");
if(matrix !== 'none') {
var values = matrix.split('(')[1].split(')')[0].split(',');
var a = values[0];
var b = values[1];
var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
} else { var angle = 0; }
if(angle < 0) angle +=360;
return angle;
}
My Solution (using jQuery):
$.fn.rotationInfo = function() {
var el = $(this),
tr = el.css("-webkit-transform") || el.css("-moz-transform") || el.css("-ms-transform") || el.css("-o-transform") || '',
info = {rad: 0, deg: 0};
if (tr = tr.match('matrix\\((.*)\\)')) {
tr = tr[1].split(',');
if(typeof tr[0] != 'undefined' && typeof tr[1] != 'undefined') {
info.rad = Math.atan2(tr[1], tr[0]);
info.deg = parseFloat((info.rad * 180 / Math.PI).toFixed(1));
}
}
return info;
};
Usage:
$(element).rotationInfo(); // {deg: 7.5, rad: 0.13089969389957515}
$(element).rotationInfo().deg; // 7.5
Here is a plug-in version of Twist's function. Also, the conditional if(matrix !== 'none') did not work for me. So I have added type-checking:
(function ($) {
$.fn.rotationDegrees = function () {
var matrix = this.css("-webkit-transform") ||
this.css("-moz-transform") ||
this.css("-ms-transform") ||
this.css("-o-transform") ||
this.css("transform");
if(typeof matrix === 'string' && matrix !== 'none') {
var values = matrix.split('(')[1].split(')')[0].split(',');
var a = values[0];
var b = values[1];
var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
} else { var angle = 0; }
return angle;
};
}(jQuery));
Use as follows:
var rotation = $('img').rotationDegrees();
The CSS tranform property will always return a matrix value, as rotate, skew, scale etc. is just shorthand for doing things easier, and not having to calculate the matrix value everytime, however the matrix is calculated by the browser and applied as a matrix, and when that is done it can no longer return the rotated degree by angle without recalculating the matrix back again.
To make such calcualtions easier there is a javascript library called Sylvester that was created for the purpose of easy matrix calculation, try looking at that to get the rotation degree from the matrix value.
Also, if you where to write a rotate function in javascript to translate rotational degrees to a matrix, it would probably look something like this (this uses sylvester for the last calculation) :
var Transform = {
rotate: function(deg) {
var rad = parseFloat(deg) * (Math.PI/180),
cos_theta = Math.cos(rad),
sin_theta = Math.sin(rad);
var a = cos_theta,
b = sin_theta,
c = -sin_theta,
d = cos_theta;
return $M([
[a, c, 0],
[b, d, 0],
[0, 0, 1]
]);
}
};
Now all you really have to do is reverse enginer that function and you're golden :-)
This script is very helpful
https://github.com/zachstronaut/jquery-css-transform
I have make a fiddle with this working code to get rotateX Y Z on a 3D , or rotateZ for a 2D transform. Thanks to mihn for the base code that i have little updated with actual jquery 2.2.3.
I currently use this solution for my own projects.
https://jsfiddle.net/bragon95/49a4h6e9/
//
//Thanks: Adapted on base code from mihn http://stackoverflow.com/a/20371725
//
function getcsstransform(obj)
{
var isIE = /(MSIE|Trident\/|Edge\/)/i.test(navigator.userAgent);
var TType="undefined",
rotateX = 0,
rotateY = 0,
rotateZ = 0;
var matrix = obj.css("-webkit-transform") ||
obj.css("-moz-transform") ||
obj.css("-ms-transform") ||
obj.css("-o-transform") ||
obj.css("transform");
if (matrix!==undefined && matrix !== 'none')
{
// if matrix is 2d matrix
TType="2D";
if (matrix.indexOf('matrix(') >= 0)
{
var values = matrix.split('(')[1].split(')')[0];
if (isIE) //case IE
{
angle = parseFloat(values.replace('deg', STR_EMPTY));
}else
{
values = values.split(',');
var a = values[0];
var b = values[1];
var rotateZ = Math.round(Math.atan2(b, a) * (180 / Math.PI));
}
}else
{
// matrix is matrix3d
TType="3D";
var values = matrix.split('(')[1].split(')')[0].split(',');
var sinB = parseFloat(values[8]);
var b = Math.round(Math.asin(sinB) * 180 / Math.PI);
var cosB = Math.cos(b * Math.PI / 180);
var matrixVal10 = parseFloat(values[9]);
var a = Math.round(Math.asin(-matrixVal10 / cosB) * 180 / Math.PI);
var matrixVal1 = parseFloat(values[0]);
var c = Math.round(Math.acos(matrixVal1 / cosB) * 180 / Math.PI);
rotateX = a;
rotateY = b;
rotateZ = c;
}
}
return { TType: TType, rotateX: rotateX, rotateY: rotateY, rotateZ: rotateZ };
};
mAngle = getcsstransform($("#Objet3D"));
if (mAngle.TType=="2D")
{
$("#Result").html("Transform 2D [rotateZ=" + mAngle.rotateZ + "°]");
}else
{
$("#Result").html("Transform 3D [rotateX=" + mAngle.rotateX + "°|rotateY=" + mAngle.rotateY + "°|rotateZ=" + mAngle.rotateZ + "°]");
}
If you do this in the way you described, any this is the only place where you actually modify transform of the object, then since your browser can not be all 4 kinds of browsers at the same time, some of the prefixed values you assigned are still exactly as you assigned them.
So for example if you use webkit, then this.css('-o-transform') will still return 'rotate(7.5deg)', so it is just a matter of matching it against /rotate\((.*)deg\)/.
This worked fine for me : I always assign 5 css styles, and read back all five styles, hoping that at least one of them will be untouched. I am not sure if this works if the styles are set in CSS (not in JS) though.
Also you could replace var angle = Math.round(Math.atan2(b, a) * (180/Math.PI)); to var angle = Math.round(Math.acos(a) * (180/Math.PI));
Since I constantly need to use jQuery together with TweenMax and since TweenMax already took care of all the parsing of various types of transformation strings as well as compatibility issues, I wrote a tiny jquery plugin here (more of a wrap up of gsap's) that could directly access these values like this:
$('#ele').transform('rotationX') // returns 0
$('#ele').transform('x') // returns value of translate-x
The list of properties you could get/set, along with their initial properties:
perspective: 0
rotation: 0
rotationX: 0
rotationY: 0
scaleX: 1
scaleY: 1
scaleZ: 1
skewX: 0
skewY: 0
x: 0
y: 0
z: 0
zOrigin: 0
Paste from my other answer, hope this helps.
If you're willing to use in-line styling for just this transformation, then you can use jQuery to get the contents of the style tag:
parseInt($( /*TODO*/ ).attr('style').split('rotate(')[1].split('deg)')[0]);

HTML5 Canvas, replacing colors in an image not working on some machines

I have a 2d RTS HTML5 / Javascript game. I use images to display the player's units and buildings. I provide the image and then use a script to replace certain colors in the images with other color, to get different versions of an image with different colors (so the soldier of player 1 has a red sword and the soldier of player 2 has a blue sword and so on...).
The problem is, for maybe ~20% of the users this replacing thing doesnt work and they see all units in the same (default) color. Im now wondering why this is. Heres the function i use to replayce the colors:
// returns a image with some colors replaced, specified by search and replace, which are arrays of color arrays ([[255, 255, 255], [...], ...], )
ImageTransformer.replaceColors = function(img, search, replace)
{
var canv = document.createElement('canvas');
canv.height = img.height;
canv.width = img.width
var ctx = canv.getContext('2d');
ctx.drawImage(img, 0, 0);
var imgData = ctx.getImageData(0, 0, canv.width, canv.height);
for(var i = 0; i < imgData.data.length; i += 4)
for(var k = 0; k < search.length; k++)
if(imgData.data[i] == search[k][0] && imgData.data[i + 1] == search[k][1] && imgData.data[i + 2] == search[k][2])
{
imgData.data[i] = replace[k][0];
imgData.data[i + 1] = replace[k][1];
imgData.data[i + 2] = replace[k][2];
}
ctx.putImageData(imgData, 0, 0);
return canv;
}
Browsers may or may not apply a gamma to the image prior to drawing them, the intent is to have more natural colors (...).
I bet this is the Browsers which apply a gama that fool your algorithm.
Rather than test for strict equality, you might use a color distance, and decide of a threshold to decide wether to switch or not :
var imgData = ctx.getImageData(0, 0, canv.width, canv.height);
var data = imgData.data, length = imgData.data.length ;
for(var k = 0; k < search.length; k++) {
var thisCol = search[k];
for(var i = 0; i < length; i += 4) {
var colDist = Math.abs(data[i] - thisCol[0] )
+ Math.abs(data[i+1] - thisCol[1] )
+ Math.abs(data[i+2] - thisCol[2] );
if( colDist < 5 )
{
data[i] = thisCol[0];
data[i + 1] = thisCol[1];
data[i + 2] = thisCol[2];
}
}
}
ctx.putImageData(imgData, 0, 0);
return canv;
(here i used as distance the sum of absolute differences in between r,g,b ; as #MarkE suggest, you can choose others, euclidian being this:
var colDist = sq(data[i] - thisCol[0] )
+ sq(data[i+1] - thisCol[1] )
+ sq(data[i+2] - thisCol[2] );
// notice this is the squared euclidian distance.
// whith function sq(x) { return x*x }
test several pictures / distances, and see what fits.
test several threshold also.
).

Raphael JS Text Along path

I am looking for an example or some confirmation on a concept. Looking to use Raphael JS on an app and want to be able to warp text similar to how graphic design applications such as Illustrator do.
Here's an adaptation of Chris Wilson's code, refactored as a drop-in function, with added features:
IE8 / VML mode support and Gecko/Firefox support (by defining the rotation origin - without this, IE8 and Firefox go nuts throwing the text all around the page)
A small adjustment to make text less ugly in Gecko browsers (e.g. Firefox) - without this, these increase the letter spacing arbitrarily
Support for manually defined font sizes and letter spacing, as well as dynamic 'fill the path' sizes and spacing
Support for manual kerning (fine-tuning letter spacing character by character). Text on a path often creates really ugly letter spaces; this allows you to define manual tweaks to fix these, by:
Numeric position in the string, or,
Character, or,
Character pairs (applying to instances of a character based on the preceding character, e.g. the below example tightens 'ae' pairs and widens 'rn' pairs)
JSBIN DEMO
function textOnPath( message, path, fontSize, letterSpacing, kerning, geckoKerning) {
// only message and path are required, other args are optional
// if fontSize or letterSpacing are undefined, they are calculated to fill the path
// 10% of fontSize is usually good for manual letterspacing
// Gecko, i.e. Firefox etc, inflates and alters the letter spacing
var gecko = /rv:([^\)]+)\) Gecko\/\d{8}/.test(navigator.userAgent||'') ? true : false;
var letters = [], places = [], messageLength = 0;
for (var c=0; c < message.length; c++) {
var letter = paper.text(0, 0, message[c]).attr({"text-anchor" : "middle"});
letters.push(letter);
if (kerning) {
if(gecko && geckoKerning) {
kerning = geckoKerning;
}
var character = letter.attr('text'), kern = 0;
var predecessor = letters[c-1] ? letters[c-1].attr('text') : '';
if (kerning[c]) {
kern = kerning[c];
} else if (kerning[character]) {
if( typeof kerning[character] === 'object' ) {
kern = kerning[character][predecessor] || kerning[character]['default'] || 0;
} else {
kern = kerning[character];
}
}
if(kerning['default'] ) {
kern = kern + (kerning['default'][predecessor] || 0);
}
messageLength += kern;
}
places.push(messageLength);
//spaces get a width of 0, so set min at 4px
messageLength += Math.max(4.5, letter.getBBox().width);
}
if( letterSpacing ){
if (gecko) {
letterSpacing = letterSpacing * 0.83;
}
} else {
letterSpacing = letterSpacing || path.getTotalLength() / messageLength;
}
fontSize = fontSize || 10 * letterSpacing;
for (c = 0; c < letters.length; c++) {
letters[c].attr("font-size", fontSize + "px");
p = path.getPointAtLength(places[c] * letterSpacing);
var rotate = 'R' + (p.alpha < 180 ? p.alpha + 180 : p.alpha > 360 ? p.alpha - 360 : p.alpha )+','+p.x+','+p.y;
letters[c].attr({ x: p.x, y: p.y, transform: rotate });
}
}
This isn't too difficult using path.getPointAtLength, as Kevin Nielsen suggests:
path = paper.path("M50,100c40,-50 270,50 300,0").attr("stroke", "#CCC");
message = "I want to do this in RaphaelJS";
//since not every letter is the same width, get the placement for each letter
//along the length of the string
//however, Raphael appears to group the width of letters into intervals of 4px,
//so this won't be perfect
for (; c < message.length; c += 1) {
letter = paper.text(0, 0, message[c]).attr({"text-anchor" : "start"});
letters.push(letter);
places.push(message_length);
//spaces get a width of 0, so set min at 4px
message_length += Math.max(4, letter.getBBox().width);
}
ratio = path.getTotalLength() / message_length;
fontsize = 10 * ratio;
for (c = 0; c < letters.length; c += 1) {
letters[c].attr("font-size", fontsize + "px");
p = path.getPointAtLength(places[c] * ratio);
//there does appear to be a bug in p.alpha around 180. Here's the fix
letters[c].attr({ x: p.x, y: p.y, transform: 'r' + (p.alpha < 180 ? p.alpha + 180 : p.alpha)});
}
jsFiddle

JavaScript (SVG drawing): Positioning x amount of points in an area

I'm using http://raphaeljs.com/ to try and draw multiple small circles. The problem I'm having is that the canvas has a fixed width, and if I want to draw, say, 1000 circles, they don't wrap onto a 'new line' (because you have to specify the xy position of each circle).
E.g.
I want this:
..................................................
to look like this:
............................
......................
At the moment I'm doing this:
for ( var i = 0; i < 1000; i++ ) {
var multiplier = i*3;
if ( i <= 50 ) {
paper.circle((2*multiplier),2,2);
} else if ( i >= 51 && i <= 101 ) {
paper.circle((2*multiplier) - 304,8,2);
} else if ( i >= 152 && i <= 202 ) {
paper.circle((2*multiplier) - 910,14,2);
}
}
For reference: circle(x co-ord, y co-ord, radius)
This is messy. I have to add an if statement for every new line I want. Must be a better way of doing it..?
You want modulo.
I'm not sure exactly what your bounding box is, but something like:
var width = 300;
for (var i = 0; i < 1000; i++) {
var multiplier = i*3;
var x = 2 * multiplier * i % width;
var y = 2 + 6 * (i + 50) / 100;
}

Categories

Resources