canvas - 绘制文本
在上个例子中,简单演示了在canvas上加载图片,这个例子则在之前的基础上,使用canvas绘制文本,即在图片上加上水印。
使用以下代码,可以在canvas上绘制文本
const canvas = document.querySelector('#canvas')const c2 = canvas.getContext('2d')c2.beginPath()c2.fillStyle = '#ffff00'// 设置填充画笔颜色,即字体颜色c2.font = 'normal bold 18px serif' // 设置字体大小c2.fillText('大家好,我是itmacy', 100, 120) // 绘制 "实心" 文字,以及位置c2.closePath()
完整例子代码如下:
DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Titletitle>
head>
<body>
<canvas id="canvas" width="400" height="400">canvas><script>drawImg()function drawImg () {const canvas = document.querySelector('#canvas')const c2 = canvas.getContext('2d')const image=new Image()image.src = 'https://img0.baidu.com/it/u=741268616,1401664941&fm=253&fmt=auto&app=138&f=JPEG?w=748&h=500'// 加载原图片大小// image.onload = () => {// const _width = image.width// const _height = image.height// canvas.setAttribute('width', _width)// canvas.setAttribute('height', _height)// // 绘制图片// c2.drawImage(image, 0, 0, image.width, image.height)// }// 等比例缩放图片image.onload = () => {const _width = image.width * 0.5const _height = image.height * 0.5canvas.setAttribute('width', _width)canvas.setAttribute('height', _height)// 绘制图片c2.drawImage(image, 0, 0, image.width, image.height, 0, 0, _width, _height)// 绘制文字c2.beginPath()c2.fillStyle = '#ffff00'// 设置填充画笔颜色,即字体颜色c2.font = 'normal bold 18px serif' // 设置字体大小c2.fillText('大家好,我是itmacy', 100, 120) // 绘制 "实心" 文字;c2.closePath()}}script>
body>
html>
预览效果如下

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
