问题
I'm trying to create a grid (matrix) of squares in a given area <canvas>
with n columns and m rows, and an option to set a spacing between the squares if desired. The grid should fill squares with random coloring.
I'd also like to add a zoom function, so the colored squares will appear much bigger in a region that is double-clicked.
Can anyone suggest a good method to generate the grid and assign random colors to the squares? If you can suggest how to create the zoom effect too that would be SUPER :)
I'm new to canvas, so any method help would be great! Thanks
回答1:
It looks like from the comments you @Spencer Wieczorek have the padded-cell drawing worked out.
The key to the other part of your question is using transforms:
determine the point from which you want to scale (doubleclicking):
var scalePtX,scalePtY
.save the untransformed context state:
ctx.save();
translate by (1-zoom)*scalePoint:
ctx.translate((1-zoom)*scalePtX,(1-zoom)*scalePtY)
scale by the zoom:
ctx.scale(zoom,zoom)
draw cells using coordinates as if they were untransformed:
fillRect
restore the context to its untransformed state:
ctx.restore()
Here's the important code and a Demo: http://jsfiddle.net/m1erickson/e8bfg3h4/
function draw(){
ctx.clearRect(0,0,cw,ch);
ctx.save();
ctx.translate((1-zoom)*scalePtX,(1-zoom)*scalePtY);
ctx.scale(zoom,zoom);
ctx.globalAlpha=0.25;
for(var y=0;y<rows;y++){
for(var x=0;x<cols;x++){
ctx.fillStyle=colors[y*cols+x];
ctx.fillRect(x*(w+padding),y*(h+padding),w,h);
}}
ctx.globalAlpha=1.00;
ctx.beginPath();
ctx.arc(scalePtX,scalePtY,10,0,Math.PI*2);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
来源:https://stackoverflow.com/questions/25715049/how-to-create-nxm-html5-canvas-grid-of-objects-colored-squares