我在屏幕上随机化矩形位置时遇到问题。我有一个5 x 5网格设置与html,他们都正确格式化。然后我在这个网格中绘制条形图也可以正常工作。问题是当我想随机抖动这些物体时,它们有时会从画布上移动(向左,或仅移到顶部)。我试图通过jQuery重新定位画布,但没有成功。
另外,我觉得我的画布大小是错误的,但如果我在CSS部分中将大小设置为100%,那么条形图突然非常小,我不明白为什么。
这是有趣的代码片段。问题是"抖动"部分
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();
}
这里还有一个包含完整代码的jsfiddle:http://jsfiddle.net/msauter/pdrwwm7x/