简体   繁体   English

如何创建对象的nxm HTML5 canvas网格(彩色正方形)?

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

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. 我正在尝试在具有n列和m行的给定区域<canvas>创建正方形的网格(矩阵),并且如果需要的话,可以设置正方形之间的间距。 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 谢谢

It looks like from the comments you @Spencer Wieczorek have the padded-cell drawing worked out. 从您的@Spencer Wieczorek的评论看来,已经完成了填充单元的绘制。

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 . 确定要缩放的点(双击): var scalePtX,scalePtY

  • save the untransformed context state: ctx.save(); 保存未转换的上下文状态: ctx.save();

  • translate by (1-zoom)*scalePoint: ctx.translate((1-zoom)*scalePtX,(1-zoom)*scalePtY) 转换为(1-缩放)* scalePoint: ctx.translate((1-zoom)*scalePtX,(1-zoom)*scalePtY)

  • scale by the zoom: ctx.scale(zoom,zoom) 按缩放比例缩放: ctx.scale(zoom,zoom)

  • draw cells using coordinates as if they were untransformed: fillRect 使用坐标绘制单元格,就好像它们是未变换的一样: fillRect

  • restore the context to its untransformed state: ctx.restore() 将上下文恢复为其未转换的状态: ctx.restore()

Here's the important code and a Demo: http://jsfiddle.net/m1erickson/e8bfg3h4/ 这是重要的代码和演示: 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM