123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- export const imgToCanvas = async (url: string) => {
- const img = document.createElement('img')
- img.src = url
- img.setAttribute('crossOrigin', 'anonymous') // 防止跨域引起的 Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
- await new Promise(resolve => (img.onload = resolve))
- // 创建canvas DOM元素,并设置其宽高和图片一样
- const canvas = document.createElement('canvas')
- canvas.width = img.width
- canvas.height = img.height
- // 坐标(0,0) 表示从此处开始绘制,相当于偏移。
- let ctx = canvas.getContext('2d') as CanvasRenderingContext2D
- ctx.fillStyle = 'rgb(255, 255, 255)'
- ctx.fillStyle = '#fff'
- ctx.fillRect(0, 0, img.width, img.height)
- ctx.drawImage(img, 0, 0)
- return canvas
- }
- /* canvas添加水印
- * @param {canvas对象} canvas
- * @param {水印文字} text
- */
- export const addWatermark = (canvas, text) => {
- const ctx = canvas.getContext('2d')
- // ctx.fillStyle = '#fff'
- const water = document.createElement('canvas')
- // 小水印画布大小
- water.width = 500
- water.height = 300
- // 第一层
- const waterCtx = water.getContext('2d') as CanvasRenderingContext2D
- waterCtx.clearRect(0, 0, water.width, water.height)
- // 小水印中文字偏转角度
- waterCtx.rotate((-25 * Math.PI) / 180)
- // waterCtx.translate(-30, -30)
- waterCtx.font = '50pt Calibri' // 水印文字添加
- waterCtx.fillStyle = 'rgba(149,155,170,0.2)'
- waterCtx.fillText('酷乐秀', -10,180)
- const pat = ctx.createPattern(water, 'repeat')
- ctx.fillStyle = pat
- ctx.fillRect(0, 0, canvas.width, canvas.height)
- return canvas
- }
- export const convasToImg = canvas => {
- return canvas.toDataURL('image/png')
- }
|