How to create nxm HTML5 canvas Grid of objects (colored squares)?

99封情书 提交于 2020-01-16 17:35:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!