利用HTML5 Canvas API绘制矩形的超级攻略

2020-04-22 06:47:00易采站长站整理

我们也可以封装一下我们的矩形,代码如下:

JavaScript Code复制内容到剪贴板

<!DOCTYPE html>   
<html lang="zh">   
<head>   
    <meta charset="UTF-8">   
    <title>封装绘制矩形方法</title>   
</head>   
<body>   
<div id="canvas-warp">   
    <canvas id="canvas" style="border: 1px solid #aaaaaa; display: block; margin: 50px auto;">   
        你的浏览器居然不支持Canvas?!赶快换一个吧!!   
    </canvas>   
</div>   
  
<script>   
    window.onload = function(){   
        var canvas = document.getElementById("canvas");   
        canvas.width = 800;   
        canvas.height = 600;   
        var context = canvas.getContext("2d");   
  
        drawRect(context, 150, 50, 50, 50, "red", 5, "blue");   
        drawRect(context, 250, 50, 50, 50, "green", 5, "red");   
        drawRect(context, 350, 50, 50, 50, "yellow", 5, "black");   
    }   
  
    function drawRect(cxt, x, y, width, height, fillColor, borderWidth, borderColor){   
        cxt.beginPath();   
        cxt.moveTo(x, y);   
        cxt.lineTo(x + width, y);   
        cxt.lineTo(x + width, y + height);   
        cxt.lineTo(x, y + height);   
        cxt.lineTo(x, y);   
        cxt.closePath();   
  
        cxt.lineWidth = borderWidth;