怎样绘制矩形

有三种方法: 

1. ctx.fillRect(x, y, width, height);

2. ctx.strokeRect(x, y, width, height);

3. ctx.clearRect(x, y width, height);

 

方法1. ctx可以认为是一支画笔, 所有的和绘图有关的方法都在ctx上, 绘制矩形需要使用: ctx.fillRect(), 参数有四个, 分别为左上角xy坐标和矩形宽高.

function draw() {
    var canvas = document.getElementById('canv');
    if (!canvas.getContext) return;
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "tomato";
    //绘制矩形
    ctx.fillRect(10, 10, 110, 110);
}
draw();

 

方法2.  使用 strokeRect(x, y, width, height) 绘制矩形边框

function draw() {
    var canvas = document.getElementById('canv');
    if (!canvas.getContext) return;
    var ctx = canvas.getContext("2d");
    // 绘制矩形边框
    ctx.strokeRect(50, 50, 150, 150);
}
draw();

 

 

 

方法3. 清除矩形区域内的图形, 使其形成一个透明的矩形区域.

function draw() {
    var canvas = document.getElementById('canv');
    if (!canvas.getContext) return;
    var ctx = canvas.getContext("2d");
    // 填充一个矩形
    ctx.fillStyle = "tomato";
    ctx.fillRect(0, 0, 300, 300);
    ctx.clearRect(50, 50, 100, 100);
}
draw();

 

 

posted on 2019-09-22 20:27  aisowe  阅读(806)  评论(0编辑  收藏  举报

导航