1. 程式人生 > 其它 >Canvas學習記錄繪製七巧板(01)

Canvas學習記錄繪製七巧板(01)

技術標籤:canvascanvasjs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        #canvas {
            border: 1px solid #000;
display: block; margin: 50px auto }
</style> </head> <body> <canvas id="canvas"> 您的瀏覽器不支援 HTML5 canvas 標籤,換個瀏覽器試試. </canvas> <script> window.onload = () => { //獲取canvas標籤 var canvas = document.getElementById
('canvas'); canvas.width = 800; //設定canvas寬度 canvas.height = 800;//設定canvas高度 //獲取canvas上下文內容 var context = canvas.getContext('2d'); //每個點座標值集合 let params = [ {path: [{x: 100, y: 100}, {x: 400, y: 100}, {x: 250, y: 250}], color: "#fe665b"}, {
path: [{x: 100, y: 100}, {x: 100, y: 400}, {x: 250, y: 250}], color: "#03a697"}, {path: [{x: 400, y: 100}, {x: 325, y: 175}, {x: 325, y: 325}, {x: 400, y: 250}], color: "#ec3c60"}, {path: [{x: 400, y: 250}, {x: 250, y: 400}, {x: 400, y: 400}], color: "#f6ca2d"}, {path: [{x: 250, y: 250}, {x: 325, y: 325}, {x: 325, y: 175}], color: "#f6f020"}, {path: [{x: 100, y: 400}, {x: 250, y: 400}, {x: 175, y: 325}], color: "#f094c5"}, {path: [{x: 250, y: 250}, {x: 175, y: 325}, {x: 250, y: 400}, {x: 325, y: 325}], color: "#a796c2"}, ]; //遍歷最外層 for (let i = 0; i < params.length; i++) { draw(params[i], context); } } function draw(data, cxt) { cxt.beginPath(); //開始繪製 cxt.moveTo(data.path[0].x, data.path[0].y);//移動畫筆 for (let j = 0; j < data.path.length; j++) { cxt.lineTo(data.path[j].x, data.path[j].y); //新增一個新的座標點 (該方法並不會建立線條) cxt.fillStyle = data.color; //設定圖形填充的顏色 } cxt.closePath();//結束繪製 //儲存每一個圖形的狀態 cxt.fill(); //設定樣式為填充模式 cxt.strokeStyle = '#000'; //設定線條顏色 cxt.lineWidth = 2;//設定線條寬度 cxt.stroke(); //方法會實際地繪製出通過 moveTo() 和 lineTo() 方法定義的路徑 }
</script> </body> </html>

效果圖:
在這裡插入圖片描述