先在 html5 页面添加 canvas 元素
- <body>
- <canvas id="box" width='800' height='800'>
- <canvas>
- </body>
然后用 JS 画图
canvas 元素本身是没有画图能力的. 所有的绘制必须在 JavaScript 内部完成:
getContext('2d') 对象是内建的 HTML5 对象, 拥有多种绘制路径, 矩形, 圆形, 字符以及添加图像的方法.
- <script>
- var c = document.querySelector('#box') // 先获取 canvas 元素
- var ctx = c.getContext('2d') // 创建 context 对象
- ctx.translate(500, 500)
- setInterval(function () {
- // 黑色半圆
- ctx.rotate(Math.PI / 180)
- ctx.beginPath()
- ctx.arc(0, 0, 250, 0, Math.PI, false)
- ctx.closePath()
- ctx.fill()
- // 四分之一处黑色整圆
- ctx.beginPath()
- ctx.arc(-125, 0, 125, 0, Math.PI * 2, true)
- ctx.closePath()
- ctx.fillStyle = "black"
- ctx.fill()
- // 四分之三处白色整圆
- ctx.beginPath()
- ctx.arc(125, 0, 125, 0, Math.PI * 2, false)
- ctx.closePath()
- ctx.fillStyle = "#fff"
- ctx.fill()
- // 在绘制整圆
- ctx.beginPath()
- ctx.arc(-125, 0, 50, 0, Math.PI * 2, true)
- ctx.closePath()
- ctx.fillStyle = "#fff"
- ctx.fill()
- // 在绘制整圆
- ctx.beginPath()
- ctx.arc(125, 0, 50, 0, Math.PI * 2, false)
- ctx.closePath()
- ctx.fillStyle = "black"
- ctx.fill()
- }, 10)
- </script>
来源: http://www.jianshu.com/p/77767ae0079f