IT源码网

怎样绘制矩形

itxm 2021年03月09日 编程语言 468 0

有三种方法: 

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

 

 

评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!