图片在canvas中显示,给canvas添加文字,文字描边,将canvas保存成图片下载到本地
Posted 徐同保的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图片在canvas中显示,给canvas添加文字,文字描边,将canvas保存成图片下载到本地相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>
图片在canvas中显示,给canvas添加文字,文字描边,将canvas保存成图片下载到本地
</title>
</head>
<body>
<div>
<canvas id="canvas" width="1280" height="720"></canvas>
</div>
<script>
// base64转Blob对象
const base64ToBlob = (code) =>
let parts = code.split(;base64,)
let contentType = parts[0].split(:)[1]
let raw = window.atob(parts[1])
let rawLength = raw.length
let uint8Array = new Uint8Array(rawLength)
for (let i = 0; i < rawLength; i++)
uint8Array[i] = raw.charCodeAt(i)
return new Blob([uint8Array], type: contentType )
const download = (dataUrl, fileName) =>
let aLink = document.createElement(a)
let blob = base64ToBlob(dataUrl)
let event = document.createEvent(HTMLEvents)
event.initEvent(click, true, true)
aLink.download = fileName + . + blob.type.split(/)[1]
aLink.href = URL.createObjectURL(blob)
aLink.click()
const init = () =>
let canvas = document.getElementById(canvas)
let ctx = canvas.getContext(2d)
let image = new Image()
image.crossOrigin = anonymous
//image.src = ./1280.png
image.src =
http://localhost:85/video/grade1/chinese1-img/%E6%88%AA%E5%9B%BE%20(1).png?time=1662633780355
image.onload = function ()
ctx.drawImage(image, 1, 1)
ctx.lineWidth = 5
ctx.font = 40px Verdana
let title = 10【汉语拼音】第7课、第8课:z c s 和zh ch sh r
let tempTitleArr = []
for (let i = 0; i < title.length; i = i + 16)
let tempTitle = title.slice(i, i + 16)
tempTitleArr.push(tempTitle)
if (
tempTitleArr.length > 2 &&
tempTitleArr[tempTitleArr.length - 1].length < 8
)
tempTitleArr[tempTitleArr.length - 2] =
tempTitleArr[tempTitleArr.length - 2] +
tempTitleArr[tempTitleArr.length - 1]
tempTitleArr.splice(tempTitleArr.length - 1, 1)
console.log(tempTitleArr)
tempTitleArr.forEach((item, index) =>
ctx.strokeStyle = #ff3333
ctx.strokeText(item, 10, 100 * (index + 1))
ctx.fillStyle = #ffff00
ctx.fillText(item, 10, 100 * (index + 1))
)
const dataUrl = canvas.toDataURL(image/png)
console.log(dataUrl)
download(dataUrl, 截图)
init()
</script>
</body>
</html>
以上是关于图片在canvas中显示,给canvas添加文字,文字描边,将canvas保存成图片下载到本地的主要内容,如果未能解决你的问题,请参考以下文章