前端canvas的学习和将网页生成canvas图片

张裕  金牌会员 | 2024-8-27 22:39:22 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 571|帖子 571|积分 1713

目的



  • 终极可以实现二维码填充在指定图片位置,并且可以填充文字在图片中
  • 学习条记,个人记录,
  • 学习掘金大佬德育处主任

    • https://juejin.cn/user/2673620576140030

  • 专栏

    • https://juejin.cn/column/7113168145912692773

  • 作者堆栈

    • https://gitee.com/k21vin/thunder-monkey-canvas

第一个canvas

  1. <body>
  2.   <canvas
  3.     id="c"
  4.     width="300"
  5.     height="200"
  6.     style="border:1px solid #ccc"
  7.   ></canvas>
  8.   <script>
  9.     //获取canvas元素
  10.     const cnv = document.querySelector('#c');
  11.     //获取canvas上下文环境对象
  12.     const cxt = cnv.getContext('2d');
  13.     //绘制图形
  14.     cxt.moveTo(100,100);//起始点坐标(x,y)
  15.     cxt.lineTo(200,100);//重点坐标(x,y)
  16.     cxt.stroke();//将起点和终点链接起来
  17.   </script>
  18. </body>
复制代码

不能通过css设置画布的宽高




  1. <html lang="en">
  2. <head>
  3.   <meta charset="UTF-8">
  4.   <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5.   <title>Document</title>
  6.   <style>
  7.     #c{
  8.       width: 400px;
  9.       height: 400px;
  10.     }
  11.   </style>
  12. </head>
  13. <body>
  14.   <canvas
  15.     id="c"
  16.     style="border:1px solid #ccc"
  17.   ></canvas>
  18.   <script>
  19.     //获取canvas元素
  20.     const cnv = document.querySelector('#c');
  21.     //获取canvas上下文环境对象
  22.     const cxt = cnv.getContext('2d');
  23.     //绘制图形
  24.     cxt.moveTo(100,100);//起始点坐标(x,y)
  25.     cxt.lineTo(200,100);//重点坐标(x,y)
  26.     cxt.stroke();//将起点和终点链接起来
  27.     console.log(cnv.width);//输出300
  28.     console.log(cnv.height);//输出150
  29.   </script>
  30. </body>
  31. </html>
复制代码
canvas 的默认宽度是300px,默认高度是150px。

  • 如果使用 css 修改 canvas 的宽高(比如本例变成 400px * 400px),那宽度就由 300px 拉伸到 400px,高度由 150px 拉伸到 400px。
  • 使用 js 获取 canvas 的宽高,此时返回的是 canvas 的默认值。
坐标系



  • 这个很重要,不能弄混了
  • Canvas 使用的是 W3C 坐标系 ,也就是遵循我们屏幕、报纸的阅读风俗,从上往下,从左往右。

W3C 坐标系数学直角坐标系 的 X轴 是一样的,只是 Y轴 的反向相反。
W3C 坐标系 的 Y轴 正方向向下
绘制直线



  • 使用moveTo,lineTo,stroke即可绘制出一条直线
  1. <body>
  2.   <canvas id="c" style="border:1px solid red"></canvas>
  3.   <script>
  4.     const canvas = document.querySelector('#c');
  5.     const cxt = canvas.getContext('2d');
  6.     cxt.moveTo(100,100);//起始点坐标(x,y)
  7.     cxt.lineTo(200,100);//下一个点的坐标(x,y)
  8.     cxt.stroke();//链接起来
  9.   </script>
  10. </body>
复制代码



  • 绘制多条直线就调用多次方法即可

    • 如果绘制的坐标点出现小数点,那么将会占据多一些格子,并将颜色平均分布(大概就是这个意思)
    • https://juejin.cn/post/7115431586857746440


设置样式



  • lineWidth:线的粗细
  • strokeStyle线的颜色
  • lineCap:线帽

  1. <body>
  2.   <canvas id="c" style="border:1px solid red"></canvas>
  3.   <script>
  4.     const canvas = document.querySelector('#c');
  5.     const cxt = canvas.getContext('2d');//获取canvas上下文环境对象
  6.     cxt.moveTo(10,10);//起始点坐标(x,y)
  7.     cxt.lineTo(60,60);
  8.     //设置线条的宽度
  9.     cxt.lineWidth = 20;
  10.     //更改线条的颜色
  11.     cxt.strokeStyle = 'green';
  12.     //修改线帽
  13.     cxt.lineCap = 'round';
  14.     cxt.stroke();//链接起来
  15.   </script>
  16. </body>
复制代码

新开路径



  • 我说怎么画2条线别的一条也变粗了
  • 在绘制多条线段的同时,还要设置线段样式,通常需要开发新路径。要不然样式之间会相互污染
  • 使用 beginPath() 方法,重新开一个路径

    • 设置新线段的样式(必做项)

      • 否则会出现前面影响背面,大概背面影响前面的环境出现

    • 比如前一个线设置了strokeWidth:20,那么即使开发了新路径,不设置strokeWidth的话第二条路径还是依照strokeWidth为20举行绘制

  1. <body>
  2.   <canvas id="c" style="border:1px solid red"></canvas>
  3.   <script>
  4.     const canvas = document.querySelector('#c');
  5.     const cxt = canvas.getContext('2d');//获取canvas上下文环境对象
  6.     cxt.moveTo(10,10);//起始点坐标(x,y)
  7.     cxt.lineTo(60,60);
  8.     //设置线条的宽度
  9.     cxt.lineWidth = 20;
  10.     cxt.stroke();//链接起来
  11.     //新开一个路径
  12.     cxt.beginPath();
  13.     //设置新线段的样式
  14.     cxt.lineWidth = 1;
  15.     //更改线条的颜色
  16.     cxt.strokeStyle = 'green';
  17.     //修改线帽
  18.     cxt.lineCap = 'round';
  19.     cxt.moveTo(100,100);//起始点坐标(x,y)
  20.     cxt.lineTo(200,100);//下一个点的坐标(x,y)
  21.     cxt.stroke();//链接起来
  22.   </script>
  23. </body>
复制代码



  • 在设置 beginPath() 的同时,也各自设置样式。这样就能做到相互不影响了。
  1. <canvas id="c" width="300" height="300" style="border: 1px solid #ccc;"></canvas>
  2. <script>
  3.   const cnv = document.getElementById('c')
  4.   const cxt = cnv.getContext('2d')
  5.   cxt.moveTo(20, 100)
  6.   cxt.lineTo(200, 100)
  7.   cxt.lineWidth = 10
  8.   cxt.strokeStyle = 'pink'
  9.   cxt.stroke()
  10.   cxt.beginPath() // 重新开启一个路径
  11.   cxt.moveTo(20, 120.5)
  12.   cxt.lineTo(200, 120.5)
  13.   cxt.lineWidth = 4
  14.   cxt.strokeStyle = 'red'
  15.   cxt.stroke()
  16. </script>
复制代码
折线(特别的直线)



  • 也是使用方法moveTo,lineTo,stroke即可完成
矩形(rect)



  • 点组成线,线组成面,面构成图形,你可以使用绘制直线的方式去绘制矩形,但是有现成的方法当然有现成的
  1. <body>
  2.   <canvas id="c" style="border:1px solid red;height: 300px;width: 300px;"></canvas>
  3.   <script>
  4.     const canvas = document.querySelector('#c');
  5.     const cxt = canvas.getContext('2d');//获取canvas上下文环境对象
  6.     cxt.strokeStyle = "green";//必须要写在绘制前面
  7.     cxt.strokeRect(10, 10, 120, 100);//起始点坐标(10,10) 宽120 高100
  8.   </script>
  9. </body>
复制代码



  • 大概这么理解,直接抄他的,嘻嘻

填充矩形



  • 你可以理解为stroke都是在做描边结果的,真正要创建填充的结果还是需要使用fill开头的一些关键字
  • 需要注意的是,fillStyle 必须写在 fillRect() 之前,不然样式不生效。
  1. <body>
  2.   <canvas id="c" style="border:1px solid red;height: 300px;width: 300px;"></canvas>
  3.   <script>
  4.     const canvas = document.querySelector('#c');
  5.     const cxt = canvas.getContext('2d');//获取canvas上下文环境对象
  6.     cxt.fillStyle = "blue";//必须要写在绘制前面
  7.     cxt.fillRect(10, 10, 120, 100);//起始点坐标(10,10) 宽120 高100
  8.   </script>
  9. </body>
复制代码



  • 同时使用strokeRect()和fillRect(),则是描边+填充结果
  1. <body>
  2.   <canvas id="c" style="border:1px solid red;height: 300px;width: 300px;"></canvas>
  3.   <script>
  4.     const canvas = document.querySelector('#c');
  5.     const cxt = canvas.getContext('2d');//获取canvas上下文环境对象
  6.     cxt.fillStyle = "blue";//必须要写在绘制前面
  7.     cxt.fillRect(10, 10, 120, 100);//起始点坐标(10,10) 宽120 高100
  8.     cxt.strokeStyle = "green";
  9.     cxt.strokeRect(10, 10, 120, 100);//起始点坐标(10,10) 宽120 高100
  10.   </script>
  11. </body>
复制代码

使用rect()



  • rect() 和 fillRect() 、strokeRect() 的用法差不多,唯一的区别是:
  • strokeRect() 和 fillRect() 这两个方法调用后会立刻绘制;rect() 方法被调用后,不会立刻绘制矩形,而是需要调用 stroke() 或 fill() 辅助渲染。
  1. <body>
  2.   <canvas id="c" style="border:1px solid red;height: 300px;width: 300px;"></canvas>
  3.   <script>
  4.     const canvas = document.querySelector('#c');
  5.     const cxt = canvas.getContext('2d');
  6.     cxt.strokeStyle  = 'pink'
  7.     cxt.fillStyle = 'blue';
  8.    
  9.     cxt.rect(10, 10, 120, 100);
  10.     cxt.stroke();//进行描边操作
  11.     cxt.fill();//进行填充炒作
  12.   </script>
  13. </body>
复制代码

clearRect()



  • 清空指定区域
  1. clearRect(x, y, width, height)
复制代码
  1. <body>
  2.   <canvas id="c" style="border:1px solid red;height: 300px;width: 300px;"></canvas>
  3.   <script>
  4.     const canvas = document.querySelector('#c');
  5.     const cxt = canvas.getContext('2d');
  6.     cxt.strokeStyle  = 'pink'
  7.     cxt.fillStyle = 'blue';
  8.    
  9.     cxt.rect(10, 10, 120, 100);
  10.     cxt.stroke();//进行描边操作
  11.     cxt.fill();//进行填充炒作
  12.    
  13.     //清空矩形
  14.     cxt.clearRect(20, 20, 100, 80);
  15.   </script>
  16. </body>
复制代码



  • 也可以使用clearRect来清空当前矩形
  1. const cnv = document.querySelector('#c');
  2. const cxt = cnv.getContext('2d');
  3. cxt.clearRect(0, 0, cnv.width, cnv.height)
复制代码
多边形



  • Canvas 要画多边形,需要使用 moveTo() 、 lineTo() 和 closePath()

    • 需要真正闭合,使用 closePath() 方法。不要本技艺动去连接2点

三角形

  1. <body>
  2.   <canvas id="canvas" width="400" height="300" style="border: 1px solid red;"></canvas>
  3.   <script>
  4.     const canvas = document.getElementById('canvas');
  5.     const ctx = canvas.getContext('2d');
  6.     ctx.lineWidth=5;//线条粗细
  7.     ctx.moveTo(10,10);
  8.     ctx.lineTo(100,100);
  9.     ctx.lineTo(300,100);
  10.     ctx.closePath();//闭合路径
  11.     ctx.stroke();//绘制路径
  12.   </script>
  13. </body>
复制代码

arc圆

  1. arc(x, y, r, sAngle, eAngle,counterclockwise)
复制代码


  • x 和 y: 圆心坐标
  • r: 半径
  • sAngle: 开始角度
  • eAngle: 结束角度
  • counterclockwise: 绘制方向(true: 逆时针; false: 顺时针),默认 false
  • 绘制圆形之前,必须先调用 beginPath() 方法!!! 在绘制完成之后,还需要调用 closePath() 方法!!!
  • 大佬的图也通俗易懂
  1. <body>
  2.   <canvas id="canvas" width="400" height="300" style="border: 1px solid red;"></canvas>
  3.   <script>
  4.     const canvas = document.getElementById('canvas');
  5.     const ctx = canvas.getContext('2d');
  6.     ctx.beginPath();
  7.     ctx.arc(100,100,50,0,Math.PI * 2);
  8.     ctx.stroke();
  9.     ctx.closePath();
  10.   </script>
  11. </body>
复制代码




  • 在实际开发中,为了让本身大概别的开发者更轻易看懂弧度的数值,1°应该写成 Math.PI / 180。(说的很好)

    • 100°: 100 * Math.PI / 180
    • 110°: 110 * Math.PI / 180
    • 241°: 241 * Math.PI / 180

  • 半圆

    • 结束角度为180度就是半圆了

  1. <body>
  2.   <canvas id="canvas" width="400" height="300" style="border: 1px solid red;"></canvas>
  3.   <script>
  4.     const canvas = document.getElementById('canvas');
  5.     const ctx = canvas.getContext('2d');
  6.     ctx.beginPath();
  7.     ctx.arc(100,100,50,0,Math.PI );
  8.     ctx.closePath();
  9.     ctx.stroke();
  10.   </script>
  11. </body>
复制代码

弧线



  • 调用arc()方法不调用closePath()方法所画出的图像就是一条弧线
  • 可用arc()大概arcTo()绘制弧线
  • arcTo语法

    • arcTo() 方法利用 开始点、控制点和结束点形成的夹角,绘制一段与夹角的两边相切并且半径为 radius 的圆弧

  1. arcTo(cx, cy, x2, y2, radius)
  2. cx: 两切线交点的横坐标
  3. cy: 两切线交点的纵坐标
  4. x2: 结束点的横坐标
  5. y2: 结束点的纵坐标
  6. radius: 半径
复制代码


  • 其中,(cx, cy) 也叫控制点,(x2, y2) 也叫结束点。
  • 是不是有点奇怪,为什么没有 x1 和 y1 ?

    • (x1, y1)是开始点,通常是由moveTo()大概lineTo()` 提供。

  • 绘制30度的弧线
  1. <body>
  2.   <canvas id="canvas" width="400" height="300" style="border: 1px solid red;"></canvas>
  3.   <script>
  4.     const canvas = document.getElementById('canvas');
  5.     const ctx = canvas.getContext('2d');
  6.     ctx.beginPath();
  7.     ctx.arc(100, 100, 50, 0, 30 * Math.PI / 180, false);
  8.     ctx.stroke();
  9.   </script>
  10. </body>
复制代码


  • 下面用arcTo方法绘制的不知道多少度,可以用数学算算
  1. <canvas id="c" width="300" height="300" style="border: 1px solid #ccc;"></canvas>
  2. <script>
  3.   const cnv = document.getElementById('c')
  4.   const cxt = cnv.getContext('2d')
  5.   cxt.moveTo(40, 40)
  6.   cxt.arcTo(120, 40, 120, 120, 80)
  7.   cxt.stroke()
  8. </script>
复制代码


  • 开始点即为(40,40)

样式设置

stroke(描边)



  • 绘制描边线条
lineWidth(设置线条宽度)



  • lineWidth = 值 + 单位
  • 设置绘制的线条宽度,默认单位为px,默认值为1
strokeStyle(描边颜色)



  • strokeStyle = 颜色值
lineCap(设置线帽)



  • lineCap = 值
  • butt: 默认值,无线帽
  • square: 方形线帽
  • round: 圆形线帽
lineJoin(拐角样式)



  • lineJoin = 值


  • miter: 默认值,尖角
  • round: 圆角
  • bevel: 斜角

setLineDash(设置描边虚线)



  • setLineDash([])传入数组,且元素是数值型
  • 只传1个值代表空缺值(单位为px)
  • 有2个值代表线条值,空缺值,
  • 有3个以上的值线条值,空缺值,线条值依次轮的去
  1. <body>
  2.   <canvas id="canvas" width="400" height="300" style="border: 1px solid red;"></canvas>
  3.   <script>
  4.     const canvas = document.getElementById('canvas');
  5.     const ctx = canvas.getContext('2d');
  6.     //基础样式
  7.     ctx.strokeStyle = 'blue';
  8.     ctx.lineWidth = 10;
  9.     ctx.moveTo(10, 10);
  10.     ctx.lineTo(290, 10);
  11.     //设置空白值为10(也就是间隔10px)
  12.     ctx.setLineDash([10])
  13.     ctx.stroke();
  14.     ctx.beginPath();
  15.     //设置线条长度为10px,空白值为5px
  16.     ctx.setLineDash([10, 5])
  17.     ctx.moveTo(10, 40);
  18.     ctx.lineTo(290, 40);
  19.     ctx.stroke();
  20.     ctx.beginPath();
  21.     //设置线条长度为10px,空白值为5px,线条长度为20px,空白值为30px,线条长度为40px,空白值为50px
  22.     ctx.setLineDash([10, 5, 20, 30, 40, 50]);
  23.     ctx.moveTo(10, 70);
  24.     ctx.lineTo(290, 70);
  25.     ctx.stroke();
  26.   </script>
  27. </body>
复制代码

fill(填充)



  • 使用 fill() 可以填充图形
  • 可以使用 fillStyle 设置填充颜色,默认是黑色。
  1. <canvas id="c" width="300" height="300" style="border: 1px solid #ccc;"></canvas>
  2. <script>
  3.   const cnv = document.getElementById('c')
  4.   const cxt = cnv.getContext('2d')
  5.   cxt.fillStyle = 'pink'
  6.   cxt.rect(50, 50, 200, 100)
  7.   cxt.fill()
  8. </script>
复制代码

非零环绕填充



  • 如果需要判定某一个区域是否需要填充颜色. 就从该区域中随机的选取一个点。从这个点拉一条直线出来, 肯定要拉到图形的外貌. 此时以该点为圆心。看穿过拉出的直线的线段. 如果是顺时针方向就记为 +1, 如果是 逆时针方向,就记为 -1. 终极看求和的结果. 如果是 0 就不填充. 如果是 非零 就填充(注意黑白0,而不是负数)
  • 代码
  1. <body>
  2.   <canvas id="canvas" width="300" height="300" style="border: 1px solid red;"></canvas>
  3.   <script>
  4.     const canvas = document.getElementById('canvas');
  5.     const ctx = canvas.getContext('2d');
  6.     ctx.moveTo(100, 100)
  7.     ctx.lineTo(300, 100)
  8.     ctx.lineTo(300, 300)
  9.     ctx.lineTo(100, 300)
  10.     ctx.closePath()
  11.     //内部的
  12.     ctx.moveTo(150, 150)
  13.     ctx.lineTo(150, 250)
  14.     ctx.lineTo(250, 250)
  15.     ctx.lineTo(250, 150)
  16.     ctx.closePath()
  17.     ctx.fill();
  18.   </script>
  19. </body>
复制代码



  • 大的正方形绘制的方向是顺时针,小的正发形绘制的方向是逆时针(因为没有调用beginPath())
  • 小的从内部出来一根线,自身为-1,外界为1相加为0,所以不填充,而大的从内部出来一根线,自身为1,无相交,相加为1,所以填充



  • 可以看下面图像

    • 1处:出来一条线,顺时针,没有相交,相加为1,所以填充了颜色
    • 2处:出来2条线,逆时针,相加-2,不为0,所以填充
    • 3处:出来2条线,-1+1即是0,为0,所以不填充




  • 更详细可以看这个博客

    • https://www.cnblogs.com/youthBlog/p/10019537.html
    • https://blog.csdn.net/weixin_44823731/article/details/106008247

文本

strokeText()描边文本和设置文本样式



  • 和 CSS 设置 font 差不多,Canvas 也可以通过 font 设置样式。
  1. cxt.font = 'font-style font-variant font-weight font-size/line-height font-family'
复制代码
  1. 如果需要设置字号 font-size,需要同时设置 font-family。
  2. cxt.font = '30px 宋体'
复制代码
  1. <body>
  2.   <canvas id="canvas" width="300" height="300" style="border: 1px solid red;"></canvas>
  3.   <script>
  4.     const canvas = document.getElementById('canvas');
  5.     const ctx = canvas.getContext('2d');
  6.     ctx.font = '60px 宋体';
  7.     ctx.strokeText("你好,世界", 10, 100);
  8.   </script>
  9. </body>
复制代码



  • 当然,你也可以设置描边颜色strokeStyle
  1. <body>
  2.   <canvas id="canvas" width="300" height="300" style="border: 1px solid red;"></canvas>
  3.   <script>
  4.     const canvas = document.getElementById('canvas');
  5.     const ctx = canvas.getContext('2d');
  6.     ctx.font = '60px 宋体';
  7.     ctx.strokeStyle = 'blue';
  8.     ctx.strokeText("你好,世界", 10, 100);
  9.   </script>
  10. </body>
复制代码

fillText-填充文本和fillStyle-填充颜色

  1. <body>
  2.   <canvas id="canvas" width="300" height="300" style="border: 1px solid red;"></canvas>
  3.   <script>
  4.     const canvas = document.getElementById('canvas');
  5.     const ctx = canvas.getContext('2d');
  6.     ctx.font = '60px 宋体';
  7.     ctx.strokeStyle = 'blue';
  8.     // ctx.strokeText("你好,世界", 10, 100);
  9.     ctx.fillStyle = 'red';
  10.     ctx.fillText('你好,世界', 10, 100);
  11.   </script>
  12. </body>
复制代码

measureText() - 获取文本信息

  1. <body>
  2.   <canvas id="canvas" width="300" height="300" style="border: 1px solid red;"></canvas>
  3.   <script>
  4.     const canvas = document.getElementById('canvas');
  5.     const ctx = canvas.getContext('2d');
  6.     ctx.font = '60px 宋体';
  7.     ctx.strokeStyle = 'blue';
  8.     // ctx.strokeText("你好,世界", 10, 100);
  9.     ctx.fillStyle = 'red';
  10.     let text = '你好,世界';
  11.     ctx.fillText(text, 10, 100);
  12.     console.log(ctx.measureText(text));
  13.   </script>
  14. </body>
复制代码
  1. {
  2.     "actualBoundingBoxAscent": 49,
  3.     "actualBoundingBoxDescent": 7,
  4.     "actualBoundingBoxLeft": -2,
  5.     "actualBoundingBoxRight": 268,
  6.     "alphabeticBaseline": 0,
  7.     "fontBoundingBoxAscent": 52,
  8.     "fontBoundingBoxDescent": 8,
  9.     "hangingBaseline": 41.6,
  10.     "ideographicBaseline": -8,
  11.     "width": 270
  12. }
复制代码
textAlign 程度对齐方式

使用 textAlign 属性可以设置文字的程度对齐方式,一共有5个值可选


  • start: 默认。在指定位置的横坐标开始。
  • end: 在指定坐标的横坐标结束。
  • left: 左对齐。
  • right: 右对齐。
  • center: 居中对齐。


  • 从上面的例子看,start 和 left 的结果似乎是一样的,end 和 right 也似乎是一样的。
  • 在大多数环境下,它们的确一样。但在某些国家大概某些场合(比如阿拉伯),阅读文字的风俗是 从右往左 时,start 就和 right 一样了,end 和 left 也一样。这是需要注意的地方。

textBaseline 垂直对齐方式



  • 使用 textBaseline 属性可以设置文字的垂直对齐方式。
  • 在使用 textBaseline 前,需要自行相识 css 的文本基线。



  • textBaseline 可选属性:

    • alphabetic: 默认。文本基线是普通的字母基线。
    • top: 文本基线是 em 方框的顶端。
    • bottom: 文本基线是 em 方框的底端。
    • middle: 文本基线是 em 方框的正中。
    • hanging: 文本基线是悬挂基线。


drawImage-渲染图片



  • 渲染图片的方式有2中,一种是在JS里加载图片再渲染,另一种是把DOM里的图片拿到 canvas 里渲染
  1. drawImage(image,dx,dy,dw,dh);
复制代码


  • image: 要渲染的图片对象。
  • dx: image 的左上角在目的画布上 X 轴坐标
  • dy: image 的左上角在目的画布上 Y 轴坐标。
  • dw 用来界说图片的宽度。(不填则默认图片宽度)
  • dh 界说图片的高度。(不填则默认图片高度)
js方式



  • 在 JS 里加载图片并渲染,有以下几个步调:

  • 创建 Image 对象
  • 引入图片
  • 等待图片加载完成(必须)
  • 使用 drawImage() 方法渲染图片
  1. <body>
  2.   <canvas id="canvas" width="800" height="500" style="border: 1px solid red;"></canvas>
  3.   <script>
  4.     const canvas = document.getElementById('canvas');
  5.     const ctx = canvas.getContext('2d');
  6.     const image = new Image();
  7.     image.src = 'https://s2.loli.net/2024/03/08/FmvSfs5TeZh4Bcq.png';
  8.     image.onload = () => {
  9.       //等待图片加载完成
  10.       ctx.drawImage(image,30,30)
  11.     }
  12.   </script>
  13. </body>
复制代码

DOM方式

  1. <body>
  2.   <img src="https://s2.loli.net/2024/03/08/FmvSfs5TeZh4Bcq.png" id="cimg"/>
  3.   <canvas id="canvas" width="800" height="500" style="border: 1px solid red;"></canvas>
  4.   <script>
  5.     const canvas = document.getElementById('canvas');
  6.     const ctx = canvas.getContext('2d');
  7.     const cimgDOM = document.getElementById('cimg');
  8.     ctx.drawImage(cimgDOM,30,30)
  9.   </script>
  10. </body>
复制代码

设置图片宽高

  1. drawImage(image, dx, dy, dw, dh)
复制代码
image、 dx、 dy 的用法和前面一样。
dw 用来界说图片的宽度,dh 界说图片的高度。
截取图片



  • 又多了参数…
  1. drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
复制代码


  • image: 图片对象
  • dx: 开始截取的横坐标
  • dy: 开始截取的纵坐标
  • dw: 截取的宽度
  • dh: 截取的高度
  • sx: 图片左上角的横坐标位置
  • sy: 图片左上角的纵坐标位置
  • sw: 图片宽度
  • sh: 图片高度
  1. <body>
  2.   <canvas id="canvas" width="400" height="400" style="border: 1px solid red;"></canvas>
  3.   <script>
  4.     const canvas = document.getElementById('canvas');
  5.     const ctx = canvas.getContext('2d');
  6.     const image = new Image();
  7.     image.src = 'https://s2.loli.net/2024/03/08/FmvSfs5TeZh4Bcq.png';
  8.     image.onload = () => {
  9.       //从图像的 (10,10) 位置开始剪切,剪切的大小为 120x300,然后在画布的 (20,30) 位置放置图像,缩放图像的大小为 100x200。
  10.       ctx.drawImage(image, 10,10,120,300,20,30,100,200)
  11.     }
  12.   </script>
  13. </body>
复制代码

  1. const canvas = document.getElementById("canvas");
  2. const ctx = canvas.getContext("2d");
  3. const image = document.getElementById("source");
  4. image.addEventListener("load", (e) => {
  5.   ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);
  6. });
复制代码

使用html2canvas



  • 很多环境下我们需要动态生成分享图片,很多环境下我们使用的是这个html2canvas的库
图片为空缺



  • 空缺大部分环境是下面几种缘故原由

    • 跨域

      • 解决,后端解决

    • 使用的是网络图片

      • 解决办法看下面

    • 图片未加载完成绩调用了方法

      • 解决,等待图片加载完成后调用

    • 滚动条的一些问题啥的

      • 解决:略


  • 一般环境下,如果是本地引入的图片,不依赖于网络,是可以正常加载的
  • 但是大部分的时候,我们使用的图片都是网络图片,也就是http大概https开头的图片,会出现图片为空缺的环境
  • 也就是将proxy设置为和图片一样的地址
终极解决-后端设置答应跨域



  • 后端开启跨域,然后前端html2canvas配置参数中的useCORS设置为true,大概你可以试试看html2canvas配置项的proxy功能

    • 如果是需要使用html2canvas的话,必须要后端设置答应跨域
    • 下面代码图床设置为了跨域,所以canvas渲染没问题

  1. <body>
  2.   <div id="main" style="width: 500px;height: 500px;display: flex;border: 1px solid red;">
  3.     <img style="width: 90%;height: 90%;" src="https://oss.dreamlove.top/i/2024/03/09/hg7kn6.jpg"  />
  4.     <div style="font-size: 20px;">大家好,我是文字</div>
  5.   </div>
  6.   <button id="clickme">点击我</button>
  7.   <script type="module">
  8.     import html2canvas from 'https://cdn.bootcdn.net/ajax/libs/html2canvas/1.4.1/html2canvas.esm.min.js';
  9.     document.getElementById('clickme').addEventListener('click', () => {
  10.       html2canvas(document.querySelector('#main'),{
  11.         useCORS: true // 【重要】开启跨域配置
  12.       }).then(function (canvas) {
  13.         document.body.append(canvas)
  14.       });
  15.     })
  16.   </script>
  17. </body>
复制代码
练习



  • 学习文章

    • https://cloud.tencent.com/developer/article/1356175

  1. <body>
  2.   <div id="wrapper"
  3.     style="position: relative;width: 600px;height: 500px;background-color: red;background-image: url('./image/bg.jpg');">
  4.     <span id="time"
  5.       style="color: blue;position: absolute;bottom: 0;font-size: 30px;left: 50%;transform: translateX(-50%);"></span>
  6.   </div>
  7.   <button id="btnDown">下载</button>
  8.   <script type="module">
  9.     import html2canvas from "https://cdn.bootcdn.net/ajax/libs/html2canvas/1.4.1/html2canvas.esm.min.js";
  10.     function dataURLtoBlob(dataurl) {
  11.       let arr = dataurl.split(','),
  12.         mime = arr[0].match(/:(.*?);/)[1],
  13.         bstr = atob(arr[1]),
  14.         n = bstr.length,
  15.         u8arr = new Uint8Array(n)
  16.       while (n--) {
  17.         u8arr[n] = bstr.charCodeAt(n)
  18.       }
  19.       return new Blob([u8arr], { type: mime })
  20.     }
  21.     function downFile (url) {
  22.       const a = document.createElement('a');
  23.       a.style.display = 'none';
  24.       a.download = 'xx';
  25.       a.href = url;
  26.       document.body.appendChild(a);
  27.       a.click();
  28.       document.body.removeChild(a);
  29.       /*
  30.       * download: HTML5新增的属性
  31.       * url: 属性的地址必须是非跨域的地址
  32.        */
  33.     };
  34.     window.onload = () => {
  35.       const timeDOM = document.querySelector('#time');
  36.       timeDOM.textContent = new Date().toLocaleString();
  37.     }
  38.     document.querySelector('#btnDown').addEventListener('click', () => {
  39.       const shareContent = document.getElementById('wrapper');//需要截图的包裹的(原生的)DOM 对象
  40.       const width = shareContent.offsetWidth; //获取dom 宽度
  41.       const height = shareContent.offsetHeight; //获取dom 高度
  42.       const canvas = document.createElement("canvas"); //创建一个canvas节点
  43.       const scale = 1; //定义任意放大倍数 支持小数
  44.       canvas.width = width * scale; //定义canvas 宽度 * 缩放
  45.       canvas.height = height * scale; //定义canvas高度 *缩放
  46.       canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
  47.       // var rect = shareContent.getBoundingClientRect();//获取元素相对于视察的偏移量
  48.       // canvas.getContext("2d").translate(-rect.left,-rect.top);//设置context位置,值为相对于视窗的偏移量负值,让图片复位
  49.       const opts = {
  50.         scale: scale, // 添加的scale 参数
  51.         canvas: canvas, //自定义 canvas
  52.         logging: true, //日志开关
  53.         width: width, //dom 原始宽度
  54.         height: height, //dom 原始高度
  55.         backgroundColor: 'transparent',
  56.       };
  57.       html2canvas(shareContent, opts).then((canvas) => {
  58.         const base64 = canvas.toDataURL();
  59.         const blob = dataURLtoBlob(base64)
  60.         const href = window.URL.createObjectURL(blob)
  61.         downFile(href,'test.png')
  62.       })
  63.     })
  64.   </script>
  65. </body>
复制代码

动态生成分享图片



  • 常见的方法使用canvas绘制全部图像,举行布局(大部分时候是小程序,似乎是因为内部哀求图片方式不同)

    • 这里推荐几个社区看的库
    • 小程序:https://github.com/Kujiale-Mobile/Painter
    • uniapp:https://ext.dcloud.net.cn/plugin?id=13451
    • 大概直接使用微信小程序官方推出的新api名叫Snapshot(2024年3月09日-现在仅在 Skyline 渲染引擎 下支持)

      • https://developers.weixin.qq.com/miniprogram/dev/api/skyline/Snapshot.html
      • https://developers.weixin.qq.com/miniprogram/dev/component/snapshot.html
      • https://mp.weixin.qq.com/s/GOzwCBpnzn51R-TBDbf2Ag

    • 大概使用微信小程序的canvas手动画

      • https://developers.weixin.qq.com/miniprogram/dev/framework/ability/canvas.html


  • 另有的可能先写好html代码结构,后使用html2canvas举行转图片

    • pc端,移动端最常用了

  • 以下面这幅图为例子

微信小程序生成-使用snapshot绘制



  • snapshot绘制需要Skyline模式下运行
  • 代码片段https://developers.weixin.qq.com/s/XOgihzmf7kPR



  • wxml
  1. <navigation-bar title="Weixin" back="{{false}}" color="black" background="#FFF"></navigation-bar>
  2. <van-popup show="{{ show }}" bind:close="onClose">
  3.   <snapshot class="share" id="downloadWrapper">
  4.     <!-- 用户基本信息 -->
  5.     <view class="share_info">
  6.       <image class="avatar" src="{{info.avatar}}" mode="aspectFill"></image>
  7.       <view class="desc">
  8.         <view class="name">{{info.name}}</view>
  9.         <view class="text">{{info.description}}</view>
  10.       </view>
  11.     </view>
  12.     <!-- 分享背景 -->
  13.     <view class="share_bg">
  14.       <image class="pic" src="{{info.bgURL}}" mode="aspectFill"></image>
  15.     </view>
  16.     <!-- 二维码和价格 -->
  17.     <view class="share_code">
  18.       <view class="price">{{'$' + info.price}}</view>
  19.       <view class="code">
  20.         <image class="pic" src="{{info.codeURL}}" mode="aspectFill"></image>
  21.       </view>
  22.     </view>
  23.   </snapshot>
  24.   <view style="text-align:center;">
  25.     <van-button type="primary" bind:tap="handleDownload">点击下载</van-button>
  26.   </view>
  27. </van-popup>
  28. <van-button type="primary" bind:click="showPopup">点击我生成海报</van-button>
复制代码


  • index.js
  1. const app = getApp()
  2. Page({
  3.   data: {
  4.     show:false,
  5.     info:{
  6.       name: "梦洁",//用户名称
  7.       description: "给你推荐了一个好东西",//描述
  8.       avatar: "https://s2.loli.net/2024/03/09/8tey3JKxCIpg4c7.png",//头像
  9.       codeURL: "https://s2.loli.net/2024/03/09/924jbZViXRUngOh.png",//二维码
  10.       bgURL: "https://s2.loli.net/2024/03/09/QhupvOzgwGmcY58.jpg",//背景图
  11.       price: "29.99"
  12.     }
  13.   },
  14.   onLoad() {
  15.     console.log('代码片段是一种迷你、可分享的小程序或小游戏项目,可用于分享小程序和小游戏的开发经验、展示组件和 API 的使用、复现开发问题和 Bug 等。可点击以下链接查看代码片段的详细文档:')
  16.     console.log('https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html')
  17.   },
  18.   showPopup() {
  19.     this.setData({ show: true });
  20.   },
  21.   onClose() {
  22.     this.setData({ show: false });
  23.   },
  24.   //点击下载
  25.   handleDownload(){
  26.     this.createSelectorQuery().select('#downloadWrapper').node().exec(res => {
  27.       const node = res[0].node;
  28.       //保存海报
  29.       node.takeSnapshot({
  30.         type:'arraybuffer',
  31.         format:"png",
  32.         success:(res) => {
  33.           //不让背景透明,就简单点改了下扩展名
  34.           const filePath = `${wx.env.USER_DATA_PATH}/生成的图片${Math.random()}.jpg`
  35.           const fs = wx.getFileSystemManager();
  36.           //将海报数据写入本地文件
  37.           fs.writeFileSync(filePath,res.data,'binary')
  38.          
  39.           //保存到本地
  40.           wx.saveImageToPhotosAlbum({
  41.             filePath,
  42.           })
  43.         },
  44.         error:(e) => {
  45.           console.log(`出错了${e}`);
  46.         }
  47.       })
  48.     })
  49.   }
  50. })
复制代码


  • index.wxss

    • 样式就迁就点吧

  1. /* page {
  2.   display: flex;
  3.   flex-direction: column;
  4.   height: 100vh;
  5. } */
  6. .scroll-area {
  7.   flex: 1;
  8.   overflow-y: hidden;
  9. }
  10. .intro {
  11.   padding: 30rpx;
  12.   text-align: center;
  13. }
  14. .share {
  15.   border: 1rpx solid red;
  16.   width: 100vw;
  17.   height: 60vh;
  18.   display: flex;
  19.   flex-direction: column;
  20. }
  21. .share_info {
  22.   display: flex;
  23.   align-items: center;
  24. }
  25. .avatar {
  26.   width: 80rpx;
  27.   height: 80rpx;
  28.   border-radius: 50%;
  29. }
  30. .desc {
  31.   font-size: 32rpx;
  32.   margin-left: 40rpx;
  33.   flex: 1;
  34. }
  35. .name {
  36.   font-weight: bold;
  37. }
  38. .text {
  39.   color: gray;
  40. }
  41. .share_bg {
  42.   flex: 1;
  43. }
  44. .share_code {
  45.   display: flex;
  46.   align-items: center;
  47.   justify-content: space-between;
  48. }
  49. .code {
  50.   text-align: right;
  51. }
  52. .code .pic {
  53.   width: 160rpx;
  54.   height: 160rpx;
  55. }
复制代码
使用html2canvas举行转图片



  • 先写好html代码结构
  • 必须要答应跨域
  • 以react函数式组件为例
  • 主入口
  1. import React, {  useState } from "react";
  2. import { Button } from "@mui/material";
  3. import Share from "./component/share";
  4. const Index = () => {
  5.   const [open,setOpen] = useState(false);
  6.   return (
  7.     <div>
  8.       <Button onClick={() => setOpen(true)}>点击我分享</Button>
  9.       {/*  分享组件 */}
  10.       { open && <Share close={() => setOpen(false)}/> }
  11.     </div>
  12.   );
  13. };
  14. export default Index;
复制代码


  • share.jsx组件
  1. import React, { useRef, useState } from "react";
  2. import { Button, Modal } from 'antd';
  3. import html2canvas from 'html2canvas';
  4. import "./share.less";
  5. const Share = ({ close }) => {
  6.   const [info, setInfo] = useState({
  7.     name: "梦洁",//用户名称
  8.     description: "给你推荐了一个好东西",//描述
  9.     avatar: "https://s2.loli.net/2024/03/09/8tey3JKxCIpg4c7.png",//头像
  10.     codeURL: "https://s2.loli.net/2024/03/09/924jbZViXRUngOh.png",//二维码
  11.     bgURL: "https://s2.loli.net/2024/03/09/QhupvOzgwGmcY58.jpg",//背景图
  12.     price: "29.99"
  13.   });
  14.   const wrapperRef = useRef();
  15.   //点击下载
  16.   const handleDownload = () => {
  17.     html2canvas(wrapperRef.current,{
  18.       useCORS:true,//确保可以下载网络图片
  19.     }).then((canvas) => {
  20.       canvas.toBlob((data) => {
  21.         const url = URL.createObjectURL(data);
  22.         const ADOM = document.createElement("a");
  23.         ADOM.href = url;
  24.         ADOM.style.display = "none";
  25.         ADOM.download = "";//避免在当前窗口打开
  26.         document.body.appendChild(ADOM);
  27.         ADOM.click();
  28.         document.body.removeChild(ADOM);
  29.       });
  30.     })
  31.   }
  32.   return (
  33.     <Modal width={"375px"} open={true} footer={null} onCancel={close}>
  34.       <div ref={wrapperRef} className="share">
  35.         {/* 用户基本信息 */}
  36.         <div className="share_info">
  37.           <img className="avatar" src={info.avatar} alt="" />
  38.           <div className="desc">
  39.             <div className="name">{info.name}</div>
  40.             <div className="text">{info.description}</div>
  41.           </div>
  42.         </div>
  43.         {/* 分享背景 */}
  44.         <div className="share_bg">
  45.           <img alt="" src={info.bgURL} />
  46.         </div>
  47.         {/* 二维码和价格 */}
  48.         <div className="share_code">
  49.           <div className="price">{ "$" + info.price }</div>
  50.           <div className='code'>
  51.             <img alt='' src={info.codeURL}/>
  52.           </div>
  53.         </div>
  54.       </div>
  55.       <div style={{textAlign:'center'}}>
  56.         <Button type={'primary'} onClick={handleDownload}>点击下载</Button>
  57.       </div>
  58.     </Modal>
  59.   );
  60. };
  61. export default Share;
复制代码


  • 这里为了方便截图,就用手机端举行操作了

基础知识点



  • 如果不在 canvas 上设置宽高,那 canvas 元素的默认宽度是300px,默认高度是150px。
  • 线条的默认宽度是 1px ,默认颜色是黑色。

    • 但由于默认环境下 canvas 会将线条的中心点和像素的底部对齐,所以会导致表现结果是 2px 和非纯黑色问题。

  • IE兼容问题

    • 暂时只有 IE 9 以上才支持 canvas 。但好消息是 IE 已经有本身的墓碑了。
    • 如需兼容 IE 7 和 8 ,可以使用 ExplorerCanvas 。但即使是使用了 ExplorerCanvas  仍然会有所限制,比如无法使用 fillText() 方法等。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

张裕

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表