企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## drawImage() 方法 drawImage() 方法一般有三种调用方式 - drawImage(image, dx, dy) - drawImage(image, dx, dy, dw, dh) - drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) ## 平铺图片 在 Canvas 中,我们可以使用 createPattern() 方法来定义图片的平铺方式 语法: ```js var pattern = cxt.createPattern(image, type) cxt.fillStyle = pattern cxt.fillRect() ``` 参数 image 表示被平铺的图像,type 表示图像平铺的方式,其可选值如下: | 属性值 | 说明 | | --- | --- | | repeat | 默认值,在水平方向和垂直方向同时平铺 | | repeat-x | 只在水平方向平铺 | | repeat-y | 只在垂直方向平铺 | | no-repeat | 只显示一次(不平铺) | ## 切割图片 可以使用 clip() 方法来切割 Canvas 中绘制的图片 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <canvas id="canvas" style="margin:0px auto; border: 1px solid gray; display: block;margin: 10px auto;"> 当前浏览器不支持Canvas </canvas> <script> window.onload = function () { const cnv = document.getElementById('canvas') const cxt = cnv.getContext('2d') cnv.width = 1200; cnv.height = 800; // 第 1 步,绘制基本图形,用于切割 cxt.beginPath() cxt.arc(500, 500, 300, 0, 360 * Math.PI / 180, true) cxt.closePath() cxt.stroke() // 第 2 步,使用 clip() 方法,使得切割区域为上面绘制的基本图形 cxt.clip() // 第 3 步,绘制一张图片 let image = new Image() image.src = "./1.jpg" image.onload = function () { cxt.drawImage(image, 0, 0) } } </script> </body> </html> ``` ![](https://img.kancloud.cn/7d/a5/7da51af65dae606d0a2be7ba784fe840_1412x891.png)