Canvas绘制多个矩形

rect.png

pug

extends _defaultPage

block link
    link(rel="stylesheet", href="./css/style.css")

block body
    canvas#canvas(style="border: 1px solid #aaaaaa; display: block; margin: 50px auto;" width="800" height="600") 你的浏览器居然不支持Canvas?!赶紧换一个吧

block script
    script
        |seajs.use('./js/main.js')

main.es6

let canvas = document.getElementById('canvas');
let t = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;

t.beginPath();
t.rect(0,0,800,600);
t.fillStyle="#e0dcd3";
t.closePath();
t.fill();

for(let i=0;i<20;i++){
    drawWhiteRect(t,300+5*i,200+5*i,200-10*i,200-10*i);
    drawWhiteBlack(t,302.5+5*i,202.5+5*i,195-10*i,195-10*i);
}

function drawWhiteRect(txc,x,y,w,h) {
    txc.beginPath();
    txc.moveTo(x, y);
    txc.lineTo(w + x, y);
    txc.lineTo(w + x, h + y);
    txc.lineTo(x, y + h);
    txc.closePath();

    txc.fillStyle = "white";

    txc.fill();
}

function drawWhiteBlack(txc,x,y,w,h) {
    txc.beginPath();
    txc.moveTo(x, y);
    txc.lineTo(w + x, y);
    txc.lineTo(w + x, h + y);
    txc.lineTo(x, y + h);
    txc.closePath();

    txc.fillStyle = "black";

    txc.fill();
}

function drawRect(txc, x, y, width, height, borderWidth, borderColor, fillColor) {
    txc.beginPath();
    txc.moveTo(x, y);
    txc.lineTo(width + x, y);
    txc.lineTo(width + x, height + y);
    txc.lineTo(x, y + height);
    txc.closePath();

    txc.lineWidth = borderWidth;
    txc.strokeStyle = borderColor;
    txc.fillStyle = fillColor;

    txc.fill();
    txc.stroke();
}

你可能感兴趣的:(Canvas绘制多个矩形)