源码:http://corehtml5canvas.com

第一章

  • 在设置 canvas 的宽度和高度时,不能使用 px 后缀
  • 默认的 canvas 元素的大小是 300 * 150 个屏幕像素
  1. const canvas = document.createElement('canvas');
  2. const ctx = canvas.getContext('2d');
  3. ctx.font = '38px Arial';
  4. ctx.fillStyle = 'cornflowerblue';
  5. ctx.strokeStyle = 'blue';
  6. ctx.fillText('Hello Canvas', canvas.width/2 -150, canvas.height/2 + 15);
  7. ctx.strokeText('Hello Canvas', canvas.width/2 -150, canvas.height/2 + 15);
  • canvas 元素实际上有两套尺寸
  • CSS设定宽高:只会改变元素本身的大小
  • 设置元素的 width 与 height:同时修改“元素本身的大小”和“元素绘图表面的大小”。当 canvas “元素的大小”不符合”元素绘图表面的大小“时,浏览器会对绘图表面进行缩放,使其符合元素的大小。
属性 描述
getContext() 返回context。每个 canvas 元素均有一个这样的环境对象,且每个环境对象均与一个 canvas 元素相关联。
toDataURL([type,quality]) 返回 data URL。可设定为 img 元素的 src 属性值。
type:指定图像的类型,如 image/jpeg 或 image/png, 默认 image/png
quality: 0-1.0 之间的 double 值,表示图像的显示质量
toBlob(cb, type, args…) cb: 浏览器会以一个指向 blob 的引用为参数,去调用该回调函数
type: 同楼上
args:同楼上quality

context

属性 简介
canvas 指向 context 所属的 canvas 对象。
可通过 context.canvas.width, context.canvas.height 来获取 canvas 的宽度与高度
fillstyle 指定 context 在后续的图形填充操作中所使用的颜色、渐变色或图案
font 指定 context 执行 fillText() 或 strokeText() 时,所使用的字型
globalAlpha 全局透明度设定。取值在 0(完全透明)-1.0 之间
globalCompositeOperation 决定浏览器某个物体绘制在其他物体之上时,所采用的绘制方式。
lineCap 决定浏览器如何绘制线段的端点。
[butt, round, square], 默认 butt
lineWidth 决定了在 canvas 中绘制线段的屏幕像素宽度。
默认值:1.0
lineJoin 决定浏览器在两条线段相交时如何绘制焦点。
[bevel,round,miter],默认 miter
miterLimit 决定浏览器如何绘制 miter 形式的线段焦点。
shadowBlur 决定浏览器该如何延伸阴影效果。值越高,阴影效果延伸的就越远。
该值不是指阴影的像素长度,而是代表高斯模糊方程式中的参数值。
默认值是0
shadowColor 决定浏览器用何种颜色绘制阴影。
通常采用半透明色作为该属性的值。
shadowOffsetX 指定阴影效果水平方向偏移量,以 px 为单位
shadowOffsetY 指定阴影效果垂直方向偏移量
strokeStyle 指定对路径进行描边时所用的绘制风格。该值可被设定为某个颜色、渐变色或图案
textAlign 决定了以 fillText()或 strokeText()方法进行绘制时,所画文本的水平对齐方式
textBaseline 决定了以 fillText()或 strokeText()方法进行绘制时,所画文本的垂直对齐方式
save() 将当前 canvas 的状态推送到一个保存 canvas 状态的堆栈顶部。
canvas 状态包括了当前的坐标变换信息、剪辑区域以及所有context的所有属性。
canvas 状态并不包括当前的路径或位图。只能通过调用 beginPath() 来重置路径。
位图是canvas 本身的一个属性,并不属于 context,但仍然可以通过 context.getImageData() 来访问它。
restore() 将 canvas 状态堆栈顶部的条目弹出,
原来保存于栈顶的那一组状态,在弹出之后,就被设置成 canvas 的当前状态了。
因此,在调用 save() 与 restore() 之间,对 canvas 状态所进行的更改,其效果只会持续至 restore()方法被调用之前。
fillText(text, x, y [, maxWidth]) 绘制字符的轮廓

兼容性

支持 IE9-

  • explorecanvas
  • Google Chrome Frame

性能

在执行到某几行特定的代码时开始分析,在执行完后就停止分析

  1. console.profile('Core HTML5 Animation, erasing the background');
  2. //. ..
  3. console.profileEnd();
  • Profiler
  • Timeline
  • jsPerf.com

基本绘制制作(时钟)

制作一个时钟案例:
时钟.gif

  1. console.log('loaded');
  2. const node = document.getElementById('app');
  3. const canvas = document.createElement('canvas');
  4. canvas.id = 'canvas';
  5. const ctx = canvas.getContext('2d');
  6. ctx.font = '38px Arial';
  7. ctx.fillStyle = 'red';
  8. ctx.strokeStyle = 'red';
  9. console.log("canvas.width:", canvas.width, "canvas.height", canvas.height)
  10. // ctx.fillText('Hello Canvas', canvas.width/2 -150, canvas.height/2 + 15);
  11. // ctx.strokeText('Hello Canvas', canvas.width/2 -150, canvas.height/2 + 15);
  12. const FONT_HEIGHT = 15;
  13. const MARGIN = 35;
  14. const HAND_TRUNCTION = canvas.width / 25;
  15. const HOUR_HAND_TRUNCATION = canvas.width / 10;
  16. const NUMERAL_SPACING = 20;
  17. const RADIUS = canvas.width/2 - MARGIN; // 半径
  18. const HAND_RADIUS = RADIUS + NUMERAL_SPACING
  19. const drawCircle = () => {
  20. ctx.beginPath();
  21. ctx.arc(canvas.width/2, canvas.height/2, RADIUS, 0, Math.PI * 2, true);
  22. ctx.stroke();
  23. }
  24. const drawNumerals = () => {
  25. const numerals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  26. ctx.font = FONT_HEIGHT + 'px Arial';
  27. let angle = 0;
  28. let numeralWidth = 0;
  29. numerals.forEach((numeral) => {
  30. angle = Math.PI/6 * (numeral - 3);
  31. numeralWidth = ctx.measureText(numeral).width;
  32. ctx.fillText(numeral,
  33. canvas.width/2 + Math.cos(angle)*(HAND_RADIUS) - numeralWidth/2,
  34. canvas.height/2 + Math.sin(angle)*(HAND_RADIUS) - FONT_HEIGHT/3,
  35. )
  36. });
  37. }
  38. const drawCenter = () => {
  39. ctx.beginPath();
  40. ctx.arc(canvas.width/2, canvas.height/2, 5, 0, Math.PI*2, true);
  41. ctx.fill();
  42. }
  43. const drawHand = (loc, isHour) => {
  44. const angle = (Math.PI*2) * (loc/60) - Math.PI/2;
  45. const handRadius = isHour ? RADIUS - HAND_TRUNCTION - HOUR_HAND_TRUNCATION : RADIUS - HAND_TRUNCTION;
  46. ctx.moveTo(
  47. canvas.width/2,
  48. canvas.height/2
  49. );
  50. ctx.lineTo(
  51. canvas.width/2 + Math.cos(angle)*handRadius,
  52. canvas.height/2 + Math.sin(angle)*handRadius,
  53. );
  54. ctx.stroke()
  55. }
  56. const drawHands = () => {
  57. const date = new Date;
  58. let hour = date.getHours();
  59. hour = hour > 12 ? hour - 12 : hour;
  60. drawHand(hour*5 + (date.getMinutes()/60)*5, true, 0.5);
  61. drawHand(date.getMinutes(), false, 0.5);
  62. drawHand(date.getSeconds(), false, 0.2);
  63. }
  64. const drawClock = () => {
  65. ctx.clearRect(0, 0, canvas.width, canvas.height);
  66. drawNumerals();
  67. drawCircle();
  68. drawCenter();
  69. drawHands();
  70. }
  71. drawClock()
  72. const loop = setInterval(drawClock, 1000);
  73. node.append(canvas)

事件

监听事件有两种方式:区别是 addEventListener 可以同时监听多个事件。

  1. canvas.onmousedown = function (e) {
  2. console.log('mousedown');
  3. }
  4. canvas.addEventListener('mousedown', (e) => console.log('mousedown'));

鼠标事件

  • mousemove
  • mouseup
  • mouseout

键盘事件

canvas 是一个不可获取焦点的元素,即无法监听键盘事件,只能通过document或window对象添加键盘事件监听器。

  • keydown
  • keypress
  • keyup

keycode 参考列表:https://developer.mozilla.org/zh-CN/docs/Web/API/KeyboardEvent/keyCode

获取可打印字符,浏览器只会在产生可打印字符时才会触发 keypress 事件:

  1. document.addEventListener('keypress', (e) => {
  2. const key = String.fromCharCode(e.which);
  3. console.log('key', key, e.keyCode)
  4. })

触摸事件

转换坐标

浏览器监听的鼠标坐标是窗口坐标(window coordinate), 而非相对于 canvas 的坐标,可以进行相应的转换。

  1. const windowToCanvas = (canvas, x, y) => {
  2. // 获取canvas的边界框(bounding box)
  3. const bbox = canvas.getBoundingClientRect();
  4. console.log('bbox', bbox);
  5. // 当canvas元素大小与绘图表面大小不相符时,对坐标进行缩放
  6. return {
  7. x: x - bbox.left * (canvas.width / bbox.width),
  8. y: y - bbox.top * (canvas.height / bbox.height)
  9. };
  10. }
  11. canvas.onmousemove = (e) => {
  12. const loc = windowToCanvas(canvas, e.clientX, e.clientY);
  13. console.log('onmousemove', 'loc', loc)
  14. }

canvas: 立即模式(immediate-mode),立刻将指定的内容绘制上去,然后忘记刚才绘制的内容,即canvas不会包含将要绘制的图形对象列表。是直接向屏幕上绘制的。更适合制作“绘画APP”,因为不需要跟踪记录用户所绘制的东西。
SVG: 保留模式(retained-mode):会维护一份所绘图形对象的列表。更适合制作“画图APP”,可以让用户操作其所创建的图形对象。

将HTML定位到Canvas上

image.png

  1. <div id="app">
  2. <div id="glasspane">
  3. <h2 class="title">Bouncing Balls</h2>
  4. <p>One hundred balls bouncing</p>
  5. <a href="" id="startButton">Start</a>
  6. </div>
  7. </div>
  1. const node = document.getElementById('app');
  2. const canvas = document.createElement('canvas');
  3. canvas.id = 'canvas';
  4. canvas.height = 320;
  5. node.append(canvas)
  1. body {
  2. background: #ddd;
  3. }
  4. #canvas {
  5. margin-left: 10px;
  6. margin-top: 10px;
  7. background: #fff;
  8. border: thin solid #aaa;
  9. }
  10. #glasspane {
  11. position: absolute;
  12. left: 50px;
  13. top: 50px;
  14. padding: 0 20px 10px 10px;
  15. background: rgba(0, 0, 0, 0.3);
  16. border: thin solid rgba(0, 0, 0, 0.6);
  17. color: #eee;
  18. font-family: sans-serif;
  19. font-style: 12px;
  20. cursor: pointer;
  21. box-shadow: rgba(0, 0, 0, 0.5) 5px 5px 20px;
  22. }
  23. #glasspane h2 {
  24. font-weight: normal;
  25. }
  26. #glasspane .title {
  27. font-size: 2em;
  28. color: rgba(255, 255, 0, 0.8);
  29. }
  30. #glasspane a:hover {
  31. color: yellow;
  32. }
  33. #glasspane a {
  34. text-decoration: none;
  35. color: #ccc;
  36. font-style: 3.5em;
  37. }
  38. #glasspane p {
  39. margin: 10px;
  40. color: rgba(65, 65, 220, 1.0);
  41. font-style: 12pt;
  42. font-family: sans-serif;
  43. }

橡皮筋式选取框(Rubberbanding)

起初,canvas显示一张图片,当选定图像的某一部分时,应用程序会将你选取的部分放大。

  1. <div id="app">
  2. <div id="controls">
  3. <input type="button" id='resetButton' value="Reset">
  4. </div>
  5. <div id="rubberbandDiv"></div>
  6. </div>
  1. // 橡皮筋式选取框 start
  2. const rubberbandDiv = document.getElementById('rubberbandDiv');
  3. const resetBtn = document.getElementById('resetButton')
  4. const image = new Image()
  5. const mousedown = {}
  6. let rubberbandRectangle = {}
  7. let dragging = false
  8. const moveRubberbandDiv = () => {
  9. console.log('moveRubberbandDiv')
  10. rubberbandDiv.style.top = rubberbandRectangle.top + 'px';
  11. rubberbandDiv.style.left = rubberbandRectangle.left + 'px';
  12. }
  13. const resizeRubberbandDiv = () => {
  14. console.log('resizeRubberbandDivs')
  15. rubberbandDiv.style.width = rubberbandRectangle.width + 'px';
  16. rubberbandDiv.style.height = rubberbandRectangle.height + 'px';
  17. }
  18. const showRubberbandDiv = () => {
  19. console.log('showRubberbandDiv')
  20. rubberbandDiv.style.display = 'inline';
  21. }
  22. const hideRubberbandDiv = () => {
  23. console.log('hideRubberbandDiv')
  24. rubberbandDiv.style.display = 'none';
  25. }
  26. const resetRubberbandRectangle = () => {
  27. console.log('resetRubberbandRectangle')
  28. rubberbandRectangle = {
  29. top : 0,
  30. left: 0,
  31. width: 0,
  32. height: 0
  33. };
  34. }
  35. // 将 DIV 元素的左上角移动到鼠标按下的地点,并使 DIV 元素可见
  36. const rubberbandStart = (x, y) => {
  37. console.log('rubberbandStart')
  38. mousedown.x = x;
  39. mousedown.y = y;
  40. rubberbandRectangle.left = mousedown.x;
  41. rubberbandRectangle.top = mousedown.y;
  42. moveRubberbandDiv()
  43. showRubberbandDiv()
  44. dragging = true;
  45. }
  46. // 会对 DIV 元素进行移动和缩放操作
  47. const rubberbandStretch = (x, y) => {
  48. console.log('rubberbandStretch')
  49. rubberbandRectangle.left = x < mousedown.x ? x : mousedown.x;
  50. rubberbandRectangle.top = y < mousedown.y ? y : mousedown.y;
  51. rubberbandRectangle.width = Math.abs(x - mousedown.x);
  52. rubberbandRectangle.height = Math.abs(y - mousedown.y);
  53. moveRubberbandDiv()
  54. resizeRubberbandDiv()
  55. }
  56. // 把选中的那部分图像放大,并绘制出来,同时将 DIV 隐藏
  57. const rubberbandEnd = () => {
  58. console.log('rubberbandEnd')
  59. const bbox = canvas.getBoundingClientRect();
  60. try {
  61. ctx.drawImage(canvas,
  62. rubberbandRectangle.left - bbox.left,
  63. rubberbandRectangle.top - bbox.top,
  64. rubberbandRectangle.width,
  65. rubberbandRectangle.height,
  66. 0,
  67. 0,
  68. canvas.width,
  69. canvas.height
  70. )
  71. } catch (e) {
  72. // suppress error message when mouse is released
  73. // outside the canvas
  74. }
  75. resetRubberbandRectangle()
  76. rubberbandDiv.style.width = 0;
  77. rubberbandDiv.style.height = 0;
  78. hideRubberbandDiv()
  79. dragging = false;
  80. }
  81. canvas.onmousedown = (e) => {
  82. // console.log('canvas.onmousemove')
  83. const x = e.clientX;
  84. const y = e.clientY;
  85. e.preventDefault();
  86. rubberbandStart(x, y);
  87. }
  88. window.onmousemove = (e) => {
  89. // console.log('window.onmousemove')
  90. const x = e.clientX;
  91. const y = e.clientY;
  92. e.preventDefault()
  93. if (dragging) {
  94. rubberbandStretch(x, y);
  95. }
  96. }
  97. window.onmouseup = (e) => {
  98. // console.log('window.onmouseup')
  99. e.preventDefault()
  100. rubberbandEnd()
  101. }
  102. image.onload = () => {
  103. console.log('image_onload')
  104. ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
  105. }
  106. resetBtn.onClick = (e) => {
  107. ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  108. ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
  109. }
  110. image.src = '//img.08087.cc/uploads/20190113/18/1547376816-OosHLDBkeP.jpg'
  111. // 橡皮筋式选取框 End

使用 toDataURL() 将 canvas 的内容打印出来

toDataURL.gif

  1. <div id="controls">
  2. <input type="button" id="snapshotButton" value="Take snapshots">
  3. </div>
  4. <img src="" alt="" id="snapshotImageElement">
  1. const snapshotBtn = document.getElementById('snapshotButton');
  2. const snapshotImgElm = document.getElementById('snapshotImageElement');
  3. let loop2 = '';
  4. snapshotBtn.onclick = (e) => {
  5. let dataUrl = '';
  6. if (snapshotBtn.value === 'Take snapshots') {
  7. dataUrl = canvas.toDataURL();
  8. clearInterval(loop2);
  9. snapshotImgElm.src = dataUrl;
  10. snapshotImgElm.style.display = 'inline';
  11. canvas.style.display = 'none';
  12. snapshotBtn.value = 'Return to Canvas';
  13. } else {
  14. canvas.style.display = 'inline';
  15. snapshotImgElm.style.display = 'none';
  16. loop2 = setInterval(drawClock, 1000);
  17. snapshotBtn.value = 'Take snapshots'
  18. }
  19. }

数学知识

角度转弧度

180 度 = 《HTML5 Canvas 核心技术》(上) - 图4 弧度
注意:JS 中的 Math.sin()、Math.cos()、Math.tan() 采用的是弧度值,而非角度值。

第二章

需求描述:

  • 对线条、弧形、圆、曲线及多边形进行描边与填充
  • 通过设置绘图环境的属性来改变所绘图形的外观
  • 绘制圆角矩形
  • 绘制并编辑贝塞尔曲线
  • 对 2d 绘制环境进行扩展,使之可以绘制虚线
  • 使用纯色、渐变色及图案来对图形进行描边及填充
  • 用阴影效果来模拟具有深度的立体图形效果
  • 在不影响背景的情况下,使用“剪辑区域”技术来擦除图形与文本
  • 实现橡皮筋式辅助线技术,以便让用户可以交互式地绘制图形
  • 在 canvas 中拖动图形对象
  • 坐标系统的变换

矩形

image.png

功能 方法 描述
清除 clearRect(double x, double y, double w, double h) 将指定矩形与当前剪辑区域相交范围内的所有像素清除。
在默认情况下,剪辑区域的大小就是整个 canvas。所以如果你没有改动剪辑区域的话,那么在参数所指范围内的所有像素都会被清除。
“清除像素”:指的是将其颜色设置为全透明的黑色。这在实际效果上就等同于“擦除”或者“清除”了某个像素,从而使得 canvas 的背景可以透过该像素显示出来。
描边 strokeRect(double x, double y, double w, double h) 使用如下属性,为指定的矩形描边:
- strokeStyle
- lineWidth
- lineJoin
- miterLimit

如果宽度或高度有一个为0的话,那么该方法将会分别绘制一条竖线或横线。
如果均为0,则不会绘制任何东西。 | | 填充 | fillRect(double x, double y, double w, double h) | 使用 fillStyle 属性填充指定的矩形。
如果宽度或高度为0,则不会进行任何绘制 |

功能 属性
描边色 strokeStyle
填充色 fillStyle
创造线性渐变 CanvasGradient createLinearGradient(
double x0, double y0,
double x1, double y1
)
填充整个canvas,通过最后一个颜色来填充渐变线以外的区域。
参数表示渐变线的两个端点。
颜色停止点(color stop) addColorStop(double x, string color)
创造放射渐变 CanvasGradient createRadialGradient(
double x0, double y0, double r0,
double x1, double y1, double r1
)
填充范围仅限于两个圆形定义的圆锥区域
  1. const node = document.getElementById('app');
  2. const canvas = document.createElement('canvas');
  3. canvas.id = 'canvas';
  4. canvas.height = 320;
  5. canvas.width = 600;
  6. const ctx = canvas.getContext('2d');
  7. ctx.lineJoin = 'round';
  8. ctx.lineWidth = 30;
  9. ctx.font = '24px Helvetica'
  10. ctx.fillText('Click anywhere to erase', 175, 40);
  11. ctx.strokeStyle = 'goldenrod'
  12. ctx.fillStyle = 'rgba(0, 0, 255, 0.5)'
  13. ctx.strokeRect(75, 100, 200, 200);
  14. ctx.fillRect(325, 100, 200, 200)

生成线性渐变色:
image.png

image.png

image.png

image.png

  1. const gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
  2. // const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
  3. // const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
  4. // const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height/2);
  5. const gradient = ctx.createRadialGradient(
  6. canvas.width/2, canvas.height, 10,
  7. canvas.width/2, 0, 100
  8. )
  9. gradient.addColorStop(0, 'blue')
  10. gradient.addColorStop(0.25, 'white')
  11. gradient.addColorStop(0.5, 'purple')
  12. gradient.addColorStop(1, 'yellow')
  13. ctx.fillStyle = gradient;
  14. ctx.fillRect(0, 0, canvas.width, canvas.height)

图案填充

  • image 元素
  • canvas 元素
  • video 元素

image.png

  1. <div id="radios">
  2. <input type="radio" id="repeatRadio" name='patternRadio' checked>repeat
  3. <input type="radio" id="repeatXRadio" name='patternRadio'>repeatX
  4. <input type="radio" id="repeatYRadio" name='patternRadio'>repeatY
  5. <input type="radio" id="noRepeatRadio" name='patternRadio'>noRepeat
  6. </div>
  1. canvas.height = 800
  2. const repeatRadio = document.getElementById('repeatRadio');
  3. const repeatXRadio = document.getElementById('repeatXRadio')
  4. const repeatYRadio = document.getElementById('repeatYRadio')
  5. const noRepeatRadio = document.getElementById('noRepeatRadio')
  6. const image = new Image()
  7. const fillCanvasWithPattern = (repeatString) => {
  8. const pattern = ctx.createPattern(image, repeatString)
  9. ctx.clearRect(0, 0, canvas.width, canvas.height)
  10. ctx.fillStyle = pattern
  11. ctx.fillRect(0, 0, canvas.width, canvas.height)
  12. ctx.fill()
  13. }
  14. repeatRadio.onclick = () => {
  15. fillCanvasWithPattern('repeat')
  16. }
  17. repeatXRadio.onclick = () => {
  18. fillCanvasWithPattern('repeat-x')
  19. }
  20. repeatYRadio.onclick = () => {
  21. fillCanvasWithPattern('repeat-y')
  22. }
  23. noRepeatRadio.onclick = () => {
  24. fillCanvasWithPattern('no-repeat')
  25. }
  26. image.src = '//timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=156878881309' +
  27. '9&di=47c2254fc9072d61558d5081bb94d45c&imgtype=0&src=http%3A%2F%2Fico.58pic.com%2' +
  28. 'Ficonset01%2Fpretty-office-9-icons%2Fgif%2F319331.gif'
  29. image.width = '10px'
  30. image.height = '10px'
  31. image.onload = (e) => {
  32. fillCanvasWithPattern('repeat')
  33. }

阴影

shadowColor 不是全透明的,其余属性中,存在一个非0值:

属性 描述
shadowColor CSS3 格式的颜色。默认值是rgba(0, 0, 0, 0)
shadowOffsetX 从图形或文本到阴影的水平像素偏移。默认值是0
shadowOffsetY 从图形或文本到阴影的垂直像素偏移。默认值是0
shadowBlur 一个与像素无关的值。该值被用于高斯模糊方程中,以便对阴影进行模糊化处理

路径

image.png
使用rect() 与 arc() 来创建路径,然后调用 stroke() 或 fill() 令其可见。

方法 描述
rect(
double x, double y,
double width, double height)
在坐标(x,y)处建立一个宽度为width、高度为height的矩形子路径。
该子路径是封闭的,而且总是按逆时针方向来创建。
arc(
double x, double y,
double radius,
double startAngle, double endAngle
[, boolean anticlockwise])
在当前路径中增加一段表示圆弧或圆形的子路径。
可通过 boolean 值来控制该段子路径的方向。false(默认)为顺时针。
如果在调用该方法时已经有其他的子路径存在,那么arc()方法则会用一条线段把已有路径的终点与这段圆弧路径的起点连接起来。
beginPath() 将当前路径中的所有子路径都清除掉,以此来重置当前路径。
closePath() 显式地封闭某段开放路径。该方法用于封闭圆弧路径以及由曲线或线段所创建的开放路径。
fill() 使用 fillStyle 对当前路径的内部进行填充。
stroke() 使用 strokeStyle 来描绘当前路径的轮廓线。
  1. const node = document.getElementById('app');
  2. const canvas = document.createElement('canvas');
  3. const ctx = canvas.getContext('2d');
  4. canvas.id = 'canvas';
  5. canvas.width = 1200
  6. canvas.height = 1000
  7. // 画笔样式
  8. ctx.font = '48pt Helvetica';
  9. ctx.strokeStyle = 'blue';
  10. ctx.fillStyle = 'red';
  11. ctx.lineWidth = '2'; // 设置线条宽度为 2
  12. // 文本
  13. ctx.strokeText('Stroke', 60, 110);
  14. ctx.fillText('Fill', 440, 110);
  15. ctx.strokeText('Stroke && Fill', 700, 110);
  16. ctx.fillText('Stroke && Fill', 700, 110);
  17. // 矩形
  18. ctx.lineWidth = '5' // 设置线条宽度为 5
  19. ctx.beginPath()
  20. ctx.rect(80, 150, 150, 100)
  21. ctx.stroke()
  22. ctx.beginPath()
  23. ctx.rect(400, 150, 150, 100)
  24. ctx.fill()
  25. ctx.beginPath()
  26. ctx.rect(750, 150, 150, 100)
  27. ctx.stroke()
  28. ctx.fill()
  29. // 开放弧形
  30. ctx.beginPath()
  31. ctx.arc(150, 370, 60, 0, Math.PI*3/2)
  32. ctx.stroke()
  33. ctx.beginPath()
  34. ctx.arc(475, 370, 60, 0, Math.PI*3/2)
  35. ctx.fill()
  36. ctx.beginPath()
  37. ctx.arc(820, 370, 60, 0, Math.PI*3/2)
  38. ctx.stroke()
  39. ctx.fill()
  40. // 封闭弧形
  41. ctx.beginPath()
  42. ctx.arc(150, 550, 60, 0, Math.PI*3/2)
  43. ctx.closePath()
  44. ctx.stroke()
  45. ctx.beginPath()
  46. ctx.arc(475, 550, 60, 0, Math.PI*3/2)
  47. ctx.closePath()
  48. ctx.fill()
  49. ctx.beginPath()
  50. ctx.arc(820, 550, 60, 0, Math.PI*3/2)
  51. ctx.closePath()
  52. ctx.stroke()
  53. ctx.fill()

非零环绕规则

image.png
有自我交叉情况的路径:对于路径中的任意给定区域,从该区域内部画一条足够长的线段,使此线段的终点完全落在路径范围之外。
将计数器初始化为 0,然后,每当这条线段与路径上的直线或曲线相交时,就改变计数器的值。如果是与路径的顺时针部分相交,则 +1,如果是与路径的逆时针部分相交,则 -1。若计数器的最终值不是 0,那么此区域就在路径里面,在调用fill()方法时,浏览器就会对其进行填充。如果最终值非0,那么此区域就不在路径内部,浏览器也就不会对其进行填充。

剪纸效果

image.png

为什么会有一根横线?
根据 Canvas 规范,当使用 arc() 方法向当前路径中增加子路径时,该方法必须将上一条子路径的终点与所画圆弧的起点相连。可以在调用 arc()前先调用 beginPath()。调用此方法会将当前路径下的所有子路径都清除掉。

  1. const drawTwoArcs = () => {
  2. ctx.beginPath()
  3. // Outer: 逆时针
  4. ctx.arc(
  5. 300, 190,
  6. 150,
  7. 0, Math.PI*2,
  8. false
  9. );
  10. // Inner: 顺时针
  11. ctx.arc(
  12. 300, 190,
  13. 100,
  14. 0, Math.PI*2,
  15. true
  16. );
  17. ctx.fill()
  18. ctx.stroke()
  19. }
  20. const draw = () => {
  21. ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  22. drawTwoArcs()
  23. }
  24. ctx.fillStyle = 'rgba(100, 140, 230, 0.5)'
  25. ctx.strokeStyle = ctx.fillStyle;
  26. draw()

image.png

  1. const node = document.getElementById('app');
  2. const canvas = document.createElement('canvas');
  3. const ctx = canvas.getContext('2d');
  4. canvas.id = 'canvas';
  5. canvas.height = 1000;
  6. const rect = (x, y, w, h, direction) => {
  7. if (direction) {
  8. // 顺时针
  9. ctx.moveTo(x, y)
  10. ctx.lineTo(x, y+h)
  11. ctx.lineTo(x + w, y + h)
  12. ctx.lineTo(x + w, y)
  13. } else {
  14. // 逆时针
  15. ctx.moveTo(x, y)
  16. ctx.lineTo(x+w, y)
  17. ctx.lineTo(x+w, y+h)
  18. ctx.lineTo(x, y+h)
  19. }
  20. ctx.closePath()
  21. }
  22. const addOuterRectPath = () => {
  23. ctx.rect(110, 25, 370, 335)
  24. }
  25. const addRectPath = () => {
  26. rect(310, 55, 70, 35, true)
  27. }
  28. const addCirclePath = () => {
  29. ctx.arc(300, 300, 40, 0, Math.PI*2, true)
  30. }
  31. const addTrianglePath = () => {
  32. ctx.moveTo(400, 200);
  33. ctx.lineTo(250, 115);
  34. ctx.lineTo(200, 200);
  35. ctx.closePath()
  36. }
  37. const drawCutouts = () => {
  38. ctx.beginPath()
  39. addOuterRectPath()
  40. addCirclePath()
  41. addRectPath()
  42. addTrianglePath()
  43. ctx.fill()
  44. }
  45. const draw = () => {
  46. ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  47. ctx.shadowColor = 'rgba(200, 200, 0, 0.5)';
  48. ctx.shadowOffsetX = 12;
  49. ctx.shadowOffsetY = 12;
  50. ctx.shadowBlur = 15;
  51. drawCutouts()
  52. }
  53. ctx.fillStyle = 'goldenrod'
  54. draw()

线段

方法 描述
moveTo(x, y) 向当前路径中增加一条子路径,该子路径只包含一个点,就是由参数传入的那个点。该方法并不会从当前路径中清除任何子路径。
lineTo(x, y) 如果当前路径中没有子路径,那么这个方法的行为与moveTo() 一样:它会创建一条新的子路径,其中包含了经由参数所传入的那个点。如果当前路径中存在子路径,那么该方法会将你所指定的那个点加入子路径中。

image.png

  1. ctx.lineWidth = 1;
  2. ctx.beginPath()
  3. ctx.moveTo(50, 50)
  4. ctx.lineTo(450, 50)
  5. ctx.stroke()
  6. ctx.strokeStyle = 'red'
  7. ctx.beginPath()
  8. ctx.moveTo(50.5, 100)
  9. ctx.lineTo(400.5, 100)
  10. ctx.stroke()

网格

image.png

  1. // 绘制网络
  2. const drawGrid = (ctx, color, stepx, stepy) => {
  3. ctx.strokeStyle = color;
  4. ctx.lineWidth = 0.5;
  5. for (let i = stepx+0.5; i < ctx.canvas.width; i+=stepx) {
  6. ctx.beginPath()
  7. ctx.moveTo(i, 0)
  8. ctx.lineTo(i, ctx.canvas.width)
  9. ctx.stroke()
  10. }
  11. for (let i = stepy+0.5; i < ctx.canvas.height; i+=stepy) {
  12. ctx.beginPath()
  13. ctx.moveTo(0, i)
  14. ctx.lineTo(ctx.canvas.width, i)
  15. ctx.stroke()
  16. }
  17. }
  18. drawGrid(ctx, 'lightgray', 10, 10)

坐标轴

image.png

  1. // 绘制坐标轴
  2. const AXIS_MARGIN = 40;
  3. const AXIS_ORIGIN = {
  4. x: AXIS_MARGIN,
  5. y: canvas.height - AXIS_MARGIN,
  6. }
  7. const AXIS_TOP = AXIS_MARGIN;
  8. const AXIS_RIGHT = canvas.width - AXIS_MARGIN;
  9. const HORIZONTAL_TICK_SPACING = 10;
  10. const VERTICAL_TICK_SPACING = 10;
  11. const AXIS_WIDTH = AXIS_RIGHT - AXIS_ORIGIN.x;
  12. const AXIS_HEIGHT = AXIS_ORIGIN.y - AXIS_TOP;
  13. const NUM_VERTICAL_TICKS = AXIS_HEIGHT / VERTICAL_TICK_SPACING;
  14. const NUM_HORIZONTAL_TICKS = AXIS_WIDTH / HORIZONTAL_TICK_SPACING;
  15. const TICK_WIDTH = 10;
  16. const TICKS_LINEWIDTH = 0.5;
  17. const TICKS_COLOR = 'navy';
  18. const AXIS_LINEWIDTH = 1.0;
  19. const AXIS_COLOR = 'blue';
  20. const drawAxes = () => {
  21. ctx.save();
  22. ctx.strokeStyle = AXIS_COLOR;
  23. ctx.lineWidth = AXIS_LINEWIDTH;
  24. drawHorizontalAxis()
  25. drawVertialAxis()
  26. ctx.lineWidth = TICKS_LINEWIDTH
  27. ctx.strokeStyle = TICKS_COLOR
  28. drawHorizontalAxisTicks()
  29. drawVerticalAxisTicks()
  30. ctx.restore()
  31. }
  32. const drawHorizontalAxis = () => {
  33. ctx.beginPath()
  34. ctx.moveTo(AXIS_ORIGIN.x, AXIS_ORIGIN.y)
  35. ctx.lineTo(AXIS_RIGHT, AXIS_ORIGIN.y)
  36. ctx.stroke()
  37. }
  38. const drawVertialAxis = () => {
  39. ctx.beginPath()
  40. ctx.moveTo(AXIS_ORIGIN.x, AXIS_ORIGIN.y)
  41. ctx.lineTo(AXIS_ORIGIN.x, AXIS_TOP)
  42. ctx.stroke()
  43. }
  44. const drawHorizontalAxisTicks = () => {
  45. let deltaX = '';
  46. for (let i = 1; i < NUM_HORIZONTAL_TICKS; ++i) {
  47. ctx.beginPath()
  48. if (i % 5 === 0) {
  49. deltaX = TICK_WIDTH;
  50. } else {
  51. deltaX = TICK_WIDTH / 2;
  52. }
  53. ctx.moveTo(
  54. AXIS_ORIGIN.x + i * HORIZONTAL_TICK_SPACING,
  55. AXIS_ORIGIN.y - deltaX
  56. );
  57. ctx.lineTo(
  58. AXIS_ORIGIN.x + i * HORIZONTAL_TICK_SPACING,
  59. AXIS_ORIGIN.y + deltaX
  60. );
  61. ctx.stroke()
  62. }
  63. }
  64. const drawVerticalAxisTicks = () => {
  65. let deltaY = '';
  66. for (let i = 1; i < NUM_HORIZONTAL_TICKS; ++i) {
  67. ctx.beginPath()
  68. if (i % 5 === 0) {
  69. deltaY = TICK_WIDTH;
  70. } else {
  71. deltaY = TICK_WIDTH / 2;
  72. }
  73. ctx.moveTo(
  74. AXIS_ORIGIN.x - deltaY,
  75. AXIS_ORIGIN.y - i * VERTICAL_TICK_SPACING
  76. );
  77. ctx.lineTo(
  78. AXIS_ORIGIN.x + deltaY,
  79. AXIS_ORIGIN.y - i * VERTICAL_TICK_SPACING
  80. );
  81. ctx.stroke()
  82. }
  83. }
  84. drawAxes()

涂鸦线条绘制

  1. const eraseAllButton = document.getElementById('eraseAllButton');
  2. const strokeStyleSelect = document.getElementById('strokeStyleSelect');
  3. const guidewireCheckbox = document.getElementById('guidewireCheckbox');
  4. let drawingSurfaceImageData = '';
  5. const mousedown = {};
  6. const rubberbandRect = {};
  7. let dragging = false;
  8. let guidewires = guidewireCheckbox.checked;
  9. const saveDrawingSurface = () => {
  10. drawingSurfaceImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  11. }
  12. const restoreDrawingSurface = () => {
  13. ctx.putImageData(drawingSurfaceImageData, 0, 0);
  14. }
  15. const updateRubberbandRect = (loc) => {
  16. rubberbandRect.width = Math.abs(loc.x - mousedown.x);
  17. rubberbandRect.height = Math.abs(loc.y - mousedown.y);
  18. if (loc.x > mousedown.x) {
  19. rubberbandRect.left = mousedown.x;
  20. } else {
  21. rubberbandRect.left = loc.x;
  22. }
  23. if (loc.y > mousedown.y) {
  24. rubberbandRect.top = mousedown.y;
  25. } else {
  26. rubberbandRect.top = loc.y;
  27. }
  28. }
  29. const drawRubberbandShape = (loc) => {
  30. ctx.beginPath()
  31. ctx.moveTo(mousedown.x, mousedown.y)
  32. ctx.lineTo(loc.x, loc.y)
  33. ctx.stroke()
  34. }
  35. const updateRubberband = (loc) => {
  36. updateRubberbandRect(loc);
  37. drawRubberbandShape(loc);
  38. }
  39. const drawHorizontalLine = (y) => {
  40. ctx.beginPath()
  41. ctx.moveTo(0, y + 0.5)
  42. ctx.lineTo(ctx.canvas.width, y+0.5)
  43. ctx.stroke()
  44. }
  45. const drawVerticalLine = (x) => {
  46. ctx.beginPath()
  47. ctx.moveTo(x+0.5, 0)
  48. ctx.lineTo(x+0.5, ctx.canvas.height)
  49. ctx.stroke()
  50. }
  51. const drawGuidewires = (x, y) => {
  52. ctx.save()
  53. ctx.strokeStyle = 'rgba(0, 0, 230, 0.4)'
  54. ctx.lineWidth = 0.5
  55. drawVerticalLine(x)
  56. drawHorizontalLine(y)
  57. ctx.restore()
  58. }
  59. canvas.onmousedown = (e) => {
  60. let loc = windowToCanvas(canvas, e.clientX, e.clientY);
  61. e.preventDefault()
  62. saveDrawingSurface()
  63. mousedown.x = loc.x;
  64. mousedown.y = loc.y;
  65. dragging = true;
  66. }
  67. canvas.onmousemove = (e) => {
  68. let loc = {};
  69. if (dragging) {
  70. e.preventDefault()
  71. loc = windowToCanvas(canvas, e.clientX, e.clientY);
  72. restoreDrawingSurface()
  73. updateRubberband(loc)
  74. if (guidewires) {
  75. drawGuidewires(loc.x, loc.y);
  76. }
  77. }
  78. }
  79. canvas.onmouseup = (e) => {
  80. let loc = windowToCanvas(canvas, e.clientX, e.clientY);
  81. restoreDrawingSurface()
  82. updateRubberband(loc)
  83. dragging = false
  84. }
  85. eraseAllButton.onclick = (e) => {
  86. ctx.clearRect(0, 0, canvas.width, canvas.height);
  87. saveDrawingSurface()
  88. }
  89. strokeStyleSelect.onchange = (e) => {
  90. ctx.strokeStyle = strokeStyleSelect.value;
  91. }
  92. guidewireCheckbox.onchange = (e) => {
  93. guidewires = guidewireCheckbox.checked;
  94. }
  95. ctx.strokeStyle = strokeStyleSelect.value;

虚线

image.png

  1. const drawDashedLine = (ctx, x1, y1, x2, y2, dashLength=5) => {
  2. const deltaX = x2 - x1;
  3. const deltaY = y2 - y1;
  4. const numDashes = Math.floor(Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)) / dashLength);
  5. for (let i = 0; i < numDashes; ++i) {
  6. ctx[i%2 === 0 ? 'moveTo' : 'lineTo'](x1 + (deltaX/numDashes)*i, y1 + (deltaY / numDashes) * i);
  7. }
  8. ctx.stroke();
  9. }
  10. ctx.lineWidth = 3;
  11. ctx.strokeStyle = 'blue';
  12. drawDashedLine(
  13. ctx,
  14. 20,
  15. 20,
  16. ctx.canvas.width - 20,
  17. 20
  18. );
  19. drawDashedLine(
  20. ctx,
  21. ctx.canvas.height - 20,
  22. ctx.canvas.width - 20,
  23. ctx.canvas.height - 20,
  24. 10
  25. );
  26. drawDashedLine(
  27. ctx,
  28. ctx.canvas.width - 20,
  29. ctx.canvas.height - 20,
  30. 20,
  31. ctx.canvas.height - 20,
  32. 15
  33. );
  34. drawDashedLine(
  35. ctx,
  36. 20,
  37. ctx.canvas.height - 20,
  38. 20,
  39. 20,
  40. 1
  41. );

扩展 CanvasRenderingContext2D 对象

  1. const moveToFunction = CanvasRenderingContext2D.prototype.moveTo;
  2. CanvasRenderingContext2D.prototype.lastMoveToLocation = {};
  3. CanvasRenderingContext2D.prototype.moveTo = (x, y) => {
  4. moveToFunction.apply(ctx, [x, y]);
  5. this.lastMoveToLocation.x = x;
  6. this.lastMoveToLocation.y = y;
  7. }
  8. CanvasRenderingContext2D.prototype.dashedLineTo = (x, y, dashLength=5) => {
  9. const startX = this.lastMoveToLocation.x;
  10. const startY = this.lastMoveToLocation.y;
  11. const deltaX = x - startX;
  12. const deltaY = y - startY;
  13. const numDashes = Math.floor(Math.sqrt(Math.pow(deltaX) + Math.pow(deltaY)) / dashLength);
  14. for (let i = 0; i < numDashes; ++i) {
  15. this[i % 2 === 0 ? 'moveTo' : 'lineTo'](startX + (deltaX / numDashes) * i, startY + (deltaY / numDashes) * i);
  16. }
  17. this.moveTo(x, y);
  18. }
  19. ctx.lineWidth = 3;
  20. ctx.strokeStyle = 'blue';
  21. ctx.moveTo(20, 20)
  22. ctx.dashedLineTo(
  23. ctx,
  24. 20,
  25. 20,
  26. ctx.canvas.width - 20,
  27. 20
  28. );
  29. ctx.dashedLineTo(
  30. ctx,
  31. ctx.canvas.height - 20,
  32. ctx.canvas.width - 20,
  33. ctx.canvas.height - 20,
  34. 10
  35. );
  36. ctx.dashedLineTo(
  37. ctx,
  38. ctx.canvas.width - 20,
  39. ctx.canvas.height - 20,
  40. 20,
  41. ctx.canvas.height - 20,
  42. 15
  43. );
  44. ctx.dashedLineTo(
  45. ctx,
  46. 20,
  47. ctx.canvas.height - 20,
  48. 20,
  49. 20,
  50. 1
  51. );

线帽与连接点

image.pngimage.png

属性 描述 类型 取值范围
lineWidth 以像素为单位的线段宽度 double 非0正数,默认值 1.0
lineCap 决定浏览器如何绘制线段的端点 DOMString butt(默认值)
round
square
lineJoin 决定浏览器如何绘制线段的连接点 DOMString round
bevel(默认值)
miter
miterLimit 斜接线长度与1/2线宽的比值。如果斜接线的长度超过了该值。浏览器就会以bevel方式来绘制线段的连接点 double 非0正数,默认值 10.0

圆弧与圆形

方法 描述
arc(
double x,
double y,
double radius,
double startAngle,
double endAngle[,
boolean counter-clockwise]
)
创建一条以(x,y)为圆心,以 radius 为半径,以 startAngle 与 endAngle 为起止角的圆弧路径。角的单位是弧度,不是角度(180角度 = 弧度)。
最后一个参数是可选的。如果为true,则按逆时针画弧,如果是 false,则按顺时针画弧。
如果在调用该方法时,当前路径中有子路径存在,那么浏览器就会将子路径的终点与所画圆弧的起点以线段相连。
arcTo(
double x1,
double y1,
double x2,
double y2,
double radius
)
参考(x1, y1) 与 (x2, y2)两个点,创建一条以 radius 为半径的圆弧路径。该圆弧与当前点到(x1, y1)点的连线相切,同时也与(x1, y1) 到(x2, y2)的连线相切。
与 arc()方法一样,如果在调用该方法时,当前路径中有子路径存在,那么浏览器将会从子路径的终点向圆弧路径的起点处画一条线段。

image.png

  1. const CENTROID_RADIUS = 10;
  2. const CENTROID_STROKE_STYLE = 'rgba(0, 0, 0, 0.5)';
  3. const CENTROID_FILL_STYLE = 'rgba(80, 190, 240, 0.6)';
  4. const RING_INNER_RADIUS = 35;
  5. const RING_OUTER_RADIUS = 55;
  6. const ANNOTATIONS_FILL_STYLE = 'rgba(0, 0, 230, 0.9)';
  7. const ANNOTATIONS_TEXT_SIZE = 12;
  8. const TICK_WIDTH = 10;
  9. const TICK_LONG_STROKE_STYLE = 'rgba(100, 140, 230, 0.9)';
  10. const TICK_SHORT_STROKE_STYLE = 'rgba(100, 140, 230, 0.7)';
  11. const TRACKING_DIAL_STROKING_STYLE = 'rgba(100, 140, 230, 0.5)';
  12. const GUIDEWIRE_STROKE_STYLE = 'goldenrod';
  13. const GUIDEWIRE_FILL_STYLE = 'rgba(250, 250, 0, 0.6)';
  14. const circle = {
  15. x: canvas.width / 2,
  16. y: canvas.height / 2,
  17. radius: 150
  18. }
  19. const drawGrid = (color, stepx, stepy) => {
  20. ctx.save()
  21. ctx.shadowColor = undefined;
  22. ctx.shadowOffsetX = 0;
  23. ctx.shadowOffsetY = 0;
  24. ctx.strokeStyle = color;
  25. ctx.fillStyle = '#fff';
  26. ctx.lineWidth = 0.5;
  27. ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  28. for (let i = stepx + 0.5; i < ctx.canvas.width; i+=stepx) {
  29. ctx.beginPath();
  30. ctx.moveTo(i, 0);
  31. ctx.lineTo(i, ctx.canvas.height);
  32. ctx.stroke();
  33. }
  34. for (let i = stepy + 0.5; i < ctx.canvas.height; i+=stepx) {
  35. ctx.beginPath();
  36. ctx.moveTo(i, 0);
  37. ctx.lineTo(ctx.canvas.width, i);
  38. ctx.stroke();
  39. }
  40. ctx.restore();
  41. }
  42. const drawCentroid = () => {
  43. ctx.beginPath()
  44. ctx.save()
  45. ctx.strokeStyle = CENTROID_STROKE_STYLE;
  46. ctx.fillStyle = CENTROID_FILL_STYLE;
  47. ctx.arc(circle.x, circle.y, CENTROID_RADIUS, 0, Math.PI*2, false)
  48. ctx.stroke()
  49. ctx.fill()
  50. ctx.restore()
  51. }
  52. const drawCentroidGuidewire = (loc) => {
  53. const angle = -Math.PI /4;
  54. let endpt = '';
  55. let radius = circle.radius + RING_OUTER_RADIUS;
  56. if (loc.x >= circle.x) {
  57. endpt = {
  58. x: circle.x + radius * Math.cos(angle),
  59. y: circle.y + radius * Math.sin(angle),
  60. }
  61. } else {
  62. endpt = {
  63. x: circle.x - radius * Math.cos(angle),
  64. y: circle.y + radius * Math.sin(angle)
  65. }
  66. }
  67. ctx.save()
  68. ctx.strokeStyle = GUIDEWIRE_STROKE_STYLE;
  69. ctx.fillStyle = GUIDEWIRE_FILL_STYLE;
  70. ctx.beginPath()
  71. ctx.moveTo(circle.x, circle.y)
  72. ctx.lineTo(endpt.x, endpt.y)
  73. ctx.stroke()
  74. ctx.beginPath()
  75. ctx.moveTo(circle.x, circle.y)
  76. ctx.lineTo(endpt.x, endpt.y)
  77. ctx.stroke()
  78. ctx.beginPath()
  79. ctx.strokeStyle = TICK_LONG_STROKE_STYLE;
  80. ctx.arc(endpt.x, endpt.y, 5, 0, Math.PI*2, false)
  81. ctx.fill()
  82. ctx.stroke()
  83. ctx.restore()
  84. }
  85. const drawRingOuterCircle = () => {
  86. ctx.shadowColor = 'rgba(0, 0, 0, 0.7)';
  87. ctx.shadowOffsetX = 3;
  88. ctx.shadowOffsetY = 3;
  89. ctx.shadowBlur = 6;
  90. ctx.strokeStyle = TRACKING_DIAL_STROKING_STYLE;
  91. ctx.beginPath();
  92. ctx.arc(circle.x, circle.y, circle.radius + RING_OUTER_RADIUS, 0, Math.PI*2, true);
  93. ctx.stroke()
  94. }
  95. const drawTickInnerCircle = () => {
  96. ctx.save()
  97. ctx.beginPath()
  98. ctx.strokeStyle = 'rgba(0, 0, 0, 0.1'
  99. ctx.arc(
  100. circle.x,
  101. circle.y,
  102. circle.radius + RING_INNER_RADIUS - TICK_WIDTH,
  103. Math.PI*2,
  104. false
  105. )
  106. ctx.stroke()
  107. ctx.restore()
  108. }
  109. const drawRing = () => {
  110. drawRingOuterCircle()
  111. ctx.strokeStyle = 'rgba(0, 0, 0, 0.1)';
  112. ctx.arc(
  113. circle.x,
  114. circle.y,
  115. circle.radius + RING_INNER_RADIUS,
  116. 0,
  117. Math.PI*2,
  118. false
  119. )
  120. }
  121. const drawTick = (angle, radius, cnt) => {
  122. const tickWidth = cnt % 4 === 0 ? TICK_WIDTH : TICK_WIDTH / 2;
  123. ctx.beginPath();
  124. ctx.moveTo(
  125. circle.x + Math.cos(angle) * (radius - tickWidth),
  126. circle.y + Math.sin(angle) * (radius - tickWidth)
  127. );
  128. ctx.lineTo(
  129. circle.x + Math.cos(angle) * radius,
  130. circle.y + Math.sin(angle) * radius
  131. );
  132. ctx.strokeStyle = TICK_SHORT_STROKE_STYLE;
  133. ctx.stroke();
  134. }
  135. const drawTicks = () => {
  136. const radius = circle.radius + RING_INNER_RADIUS;
  137. const ANGLE_MAX = 2 * Math.PI;
  138. const ANGLE_DELTA = Math.PI / 64;
  139. ctx.save();
  140. for (let angle = 0, cnt = 0; angle < ANGLE_MAX; angle+=ANGLE_DELTA, cnt++) {
  141. drawTick(angle, radius, cnt++);
  142. }
  143. ctx.restore();
  144. }
  145. const drawAnnotations = () => {
  146. const radius = circle.radius + RING_INNER_RADIUS;
  147. ctx.save();
  148. ctx.fillStyle = ANNOTATIONS_FILL_STYLE;
  149. ctx.font = ANNOTATIONS_TEXT_SIZE + 'px Helvetica';
  150. for (let angle = 0; angle < 2*Math.PI; angle+=Math.PI/8) {
  151. ctx.beginPath();
  152. ctx.fillText(
  153. (angle * 180 / Math.PI).toFixed(0),
  154. circle.x + Math.cos(angle) * (radius - TICK_WIDTH *2),
  155. circle.y + Math.sin(angle) * (radius - TICK_WIDTH *2),
  156. );
  157. ctx.restore();
  158. }
  159. }
  160. const drawDial = () => {
  161. const loc = {
  162. x: circle.x,
  163. y: circle.y,
  164. }
  165. drawCentroid();
  166. drawCentroidGuidewire(loc);
  167. drawRing();
  168. drawTickInnerCircle();
  169. drawTicks();
  170. drawAnnotations();
  171. }
  172. ctx.shadowColor = 'rgba(0, 0, 0, 0.4)'
  173. ctx.shadowOffsetX = 2;
  174. ctx.shadowOffsetY = 2;
  175. ctx.shadowBlur = 4;
  176. ctx.textAlign = 'center';
  177. ctx.textBaseline = 'middle';
  178. drawGrid('lightgray', 10, 10)
  179. drawDial();

贝塞尔曲线

  • 平方贝塞尔曲线由两个锚点及一个控制点定义
  • 立方贝塞尔曲线由两个锚点及两个控制点定义
方法 描述
quadraticCurveTo(
double cpx,
double cpy,
double x,
double y
)
创建一条表示二次方贝塞尔曲线的路径。该方法需要传入两个点:
第一个是曲线的控制点,
第二个是锚点
bezierCurveTo(
double cpx,
double cpy,
double cp2x,
double cp2y,
double x,
double y
)
创建一条代表三次方贝塞尔曲线的路径。
需要传入三个点坐标:
前两个是控制点,
最后一个点是锚点

image.png

  1. // 绘制二次方贝塞尔曲线
  2. const drawCurve = () => {
  3. ctx.fillStyle = 'cornflowerblue';
  4. ctx.strokeStyle = 'yellow';
  5. ctx.shadowColor = 'rgba(50, 50, 50, 1.0)';
  6. ctx.shadowOffsetX = 2;
  7. ctx.shadowOffsetY = 2;
  8. ctx.shadowBlur = 4;
  9. ctx.lineWidth = 20;
  10. ctx.lineCap = 'round';
  11. ctx.beginPath()
  12. ctx.moveTo(120.5, 130)
  13. ctx.quadraticCurveTo(150.8, 130, 160.6, 150.5);
  14. ctx.quadraticCurveTo(190, 250.0, 210.5, 160.5);
  15. ctx.quadraticCurveTo(240, 100.5, 290, 70.5);
  16. ctx.stroke()
  17. }
  18. drawCurve()

image.png

  1. // 绘制三次方贝塞尔曲线
  2. const endPoints = [
  3. { x: 130, y: 70 },
  4. { x: 430, y: 270 },
  5. ];
  6. const controlPoints = [
  7. { x: 130, y: 250 },
  8. { x: 450, y: 70 },
  9. ]
  10. const drawBezierCurve = () => {
  11. ctx.strokeStyle = 'blue';
  12. ctx.beginPath();
  13. ctx.moveTo(
  14. endPoints[0].x,
  15. endPoints[0].y
  16. );
  17. ctx.bezierCurveTo(
  18. controlPoints[0].x,
  19. controlPoints[0].y,
  20. controlPoints[1].x,
  21. controlPoints[1].y,
  22. endPoints[1].x,
  23. endPoints[1].y
  24. );
  25. ctx.stroke();
  26. }
  27. const drawEndPoints = () => {
  28. ctx.strokeStyle = 'blue';
  29. ctx.fillStyle = 'red';
  30. endPoints.forEach((point) => {
  31. ctx.beginPath()
  32. ctx.arc(
  33. point.x,
  34. point.y,
  35. 5,
  36. 0,
  37. Math.PI*2,
  38. false
  39. );
  40. ctx.stroke();
  41. ctx.fill();
  42. })
  43. }
  44. const drawControlPoints = () => {
  45. ctx.strokeStyle = 'yellow';
  46. ctx.fillStyle = 'blue';
  47. controlPoints.forEach((point) => {
  48. ctx.beginPath();
  49. ctx.arc(
  50. point.x,
  51. point.y,
  52. 5,
  53. 0,
  54. Math.PI*2,
  55. false
  56. );
  57. ctx.stroke();
  58. ctx.fill();
  59. })
  60. }
  61. drawControlPoints()
  62. drawEndPoints()
  63. drawBezierCurve()

任意边形

使用moveTo() 和 lineTo() 再结合一些三角函数
image.png