如何创建对象的nxm HTML5 canvas网格(彩色正方形)? [英] How to create nxm HTML5 canvas Grid of objects (colored squares)?

查看:98
本文介绍了如何创建对象的nxm HTML5 canvas网格(彩色正方形)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在具有n列和m行的给定区域<canvas>中创建正方形的网格(矩阵),并在需要时设置一个在正方形之间设置间距的选项.网格应使用随机颜色填充正方形.

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.

有人可以建议一种生成网格并将随机颜色分配给正方形的好方法吗?如果您也可以建议如何创建缩放效果,那将是SUPER:)

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

推荐答案

从您的评论看来,@ Spencer Wieczorek已完成了填充单元格的绘制.

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:

  • 确定要缩放(双击)的点:var scalePtX,scalePtY.

保存未转换的上下文状态:ctx.save();

save the untransformed context state: ctx.save();

按(1-zoom)* scalePoint转换:ctx.translate((1-zoom)*scalePtX,(1-zoom)*scalePtY)

translate by (1-zoom)*scalePoint: ctx.translate((1-zoom)*scalePtX,(1-zoom)*scalePtY)

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

使用坐标绘制单元格,就像未转换一样:fillRect

draw cells using coordinates as if they were untransformed: fillRect

将上下文恢复为未转换状态:ctx.restore()

restore the context to its untransformed state: ctx.restore()

这是重要的代码和演示: http://jsfiddle.net/m1erickson/e8bfg3h4/

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();
}

这篇关于如何创建对象的nxm HTML5 canvas网格(彩色正方形)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆