canvas基础2 -- 形状

七巧板

七巧板本质上就是 分别由几个直线 拼成一个个图形,再将这些图形结合起来

复制代码
var tangram = [
      { p: [{ x: 0, y: 0 }, { x: 800, y: 0 }, { x: 400, y: 400 }], color: "#caff67" },
      { p: [{ x: 0, y: 0 }, { x: 400, y: 400 }, { x: 0, y: 800 }], color: "#67beef" },
      { p: [{ x: 800, y: 0 }, { x: 800, y: 400 }, { x: 600, y: 600 }, { x: 600, y: 200 }], color: "#ef3d61" },
      { p: [{ x: 600, y: 200 }, { x: 600, y: 600 }, { x: 400, y: 400 }], color: "#f9f5la" },
      { p: [{ x: 400, y: 400 }, { x: 600, y: 600 }, { x: 400, y: 800 }, { x: 200, y: 600 }], color: "#a594c0" },
      { p: [{ x: 200, y: 600 }, { x: 400, y: 800 }, { x: 0, y: 800 }], color: "#fa8ecc" },
      { p: [{ x: 800, y: 400 }, { x: 800, y: 800 }, { x: 400, y: 800 }], color: "#f6ca29" }
    ]
    const canvas = document.getElementById('canvas')
    canvas.width = 800
    canvas.height = 800
    const context = canvas.getContext('2d')

    for (let i = 0; i < tangram.length; i++) {
      draw(tangram[i], context)
    }

    function draw(piece, cxt) {
      cxt.beginPath()
      cxt.moveTo(piece.p[0].x, piece.p[0].y)
      for (var i = 1; i < piece.p.length; i++) {
        cxt.lineTo(piece.p[i].x, piece.p[i].y)
      }
      cxt.closePath()

      cxt.fillStyle = piece.color
      cxt.fill()

      cxt.strokeStyle = "black"
      cxt.lineWidth = 3
      cxt.stroke()
    }

图示:

箭头

复制代码
    context.beginPath()
    context.moveTo(100, 350) 
    context.lineTo(500, 350) 
    context.lineTo(500, 200) 
    context.lineTo(700, 400)
    context.lineTo(500, 600)
    context.lineTo(500, 450)
    context.lineTo(100, 450)
    context.closePath()
    
    context.lineWidth = 5  
    context.strokeStyle = '#058'

    context.stroke() 

图示:

1

相关推荐
我命由我123451 小时前
UI 设计 7 种排列方式
xml·学习·ui·html·产品运营·产品经理·学习方法
এ慕ོ冬℘゜5 小时前
深入理解浏览器全屏 API:从 requestFullscreen 到全屏实战
开发语言·html
csuzhucong12 小时前
二十一 - 四十阶魔方
javascript·css·html
IMPYLH14 小时前
HTML 的 <main> 元素
前端·html
言乐615 小时前
Python关于老游复刻与创新2
前端·javascript·css·python·css3
软件技术NINI1 天前
传统文化html+css 5页
前端·css·html
灯澜忆梦2 天前
【基于GO的Web开发11】gin获取URL‑Path 路径参数
前端·后端·golang·html·gin
IMPYLH2 天前
HTML 的 <legend> 元素
java·前端·html
苏灿烤鱼2 天前
一个 1.7 万 Star 的开源项目,教我们怎么判断 AI 工具值不值得用
html·github·agent
Chenrunqi1352 天前
中国象棋网页版
html