I am having a problem with randomising rectangle locations on the screen. I have a 5 x 5 grid set up with in html and they are all formatted properly. I am then drawing bars into this grid which also works fine. The problem is that when I want to randomly jitter these objects they sometimes move off the canvas (to the left, or to the top only) apparently. I am trying to reposition the canvas via jQuery with no success.
Also, I have the feeling my canvas sizes are wrong but if I set the sizes to 100% in the CSS section, the bars are suddenly very small and I have no idea why.
Here is the interesting piece of the code. the problem is the "jitter" part
function drawStimulus(size, color, orientation, location){
// size for each box, refers to the first box in the first row
// box size should be around 40 on a 22inch screen in this jsfiddle
var box_size = $("#testbox").height();
var stimulus_size = box_size * size; // size is either 1 (large) or 2/3
var size_diff = box_size-stimulus_size;
var c = document.getElementById(location);
c.width = box_size;
c.height = box_size;
// if a perfect grid is not wanted, jitter bars randomly
// by a maximum of 1/3 of the box size in any direction
if(jitter){
var hjitter = rand(-box_size/3, box_size/3);
var vjitter = rand(-box_size/3, box_size/3);
c.style.left = String(c.style.left+hjitter)+"px";
c.style.top = String(c.style.top+vjitter)+"px";
}
var ctx = c.getContext("2d");
// rotate around center
ctx.translate(box_size/2, box_size/2);
ctx.rotate(orientation*Math.PI / 180);
ctx.translate(-box_size/2, -box_size/2);
// draw bars
ctx.beginPath();
ctx.strokeStyle = color;
ctx.moveTo(c.offsetLeft+size_diff/2,c.offsetTop+box_size/2);
ctx.lineTo(c.offsetLeft+stimulus_size+size_diff/2,c.offsetTop+box_size/2);
ctx.lineWidth = size*10;
ctx.closePath();
ctx.stroke();
}
Here is also a jsfiddle with the full code: http://jsfiddle.net/msauter/pdrwwm7x/