在上一篇文章中,我们了解了 canvas如何新增属性和方法来自定义扩展,这篇文章,我们引用别人的一个扩展方法,文字自动换行。具体的使用示例,请参考示例源代码。进一步的讲解,请参考后面的参考资料链接。
示例效果图
示例源代码(共86行)
/*
* @Author: 大剑师兰特(xiaozhuanlan),还是大剑师兰特(CSDN)
* @此源代码版权归大剑师兰特所有,可供学习或商业项目中借鉴,未经授权,不得重复地发表到博客、论坛,问答,git等公共空间或网站中。
* @Email: 2909222303@qq.com
* @weixin: gis-dajianshi
* @First published in CSDN
* @First published time: 2024-02-01
*/
<template>
<div class="djs_container">
<div class="top">
<h3>canvas自定义扩展:文字自动换行</h3>
<div>大剑师兰特, 还是大剑师兰特,gis-dajianshi</div>
<h4>
<el-button type="primary" size="mini" @click="draw()">绘制</el-button>
<el-button type="danger" size="mini" @click="clearCanvas()">清除</el-button>
</h4>
</div>
<div class="dajianshi ">
<canvas id="dajianshi" ref="mycanvas" width="980" height="490"></canvas>
</div>
</div>
</template>
<script>
export default {
data() {
return {
ctx: null,
canvas: null,
}
},
mounted() {
this.setCanvas()
},
methods: {
clearCanvas() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
setCanvas() {
this.canvas = document.getElementById('dajianshi');
if (!this.canvas.getContext) return;
this.ctx = this.canvas.getContext("2d");
CanvasRenderingContext2D.prototype.wrapText = function(text, x, y, maxWidth, lineHeight) {
if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
return;
}
var context = this;
var canvas = context.canvas;
if (typeof maxWidth == 'undefined') {
maxWidth = (canvas && canvas.width) || 300;
}
if (typeof lineHeight == 'undefined') {
lineHeight = (canvas && parseInt(window.getComputedStyle(canvas).lineHeight)) || parseInt(
window.getComputedStyle(document.body).lineHeight);
}
// 字符分隔为数组
var arrText = text.split('');
var line = '';
for (var n = 0; n < arrText.length; n++) {
var testLine = line + arrText[n];
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
context.fillText(line, x, y);
line = arrText[n];
y += lineHeight;
} else {
line = testLine;
}
}
context.fillText(line, x, y);
};
},
draw() {
let txt='还是大剑师兰特:美国某知名大学研究生,专业的航天航海交通领域高级前端开发工程师,从事GIS、物联网行业多年,深耕vue+openlayers,vue+cesium,vue+mapbox,vue+leaflet等领域。'
this.ctx.fillStyle = 'orange';
this.ctx.font = '28px STheiti, SimHei';
this.ctx.wrapText(txt, 340, 100, 400, 50)
},
}
}
</script>
<style scoped>
.djs_container {
width: 1000px;
height: 680px;
margin: 50px auto;
border: 1px solid #991188;
position: relative;
}
.top {
margin: 0 auto 0px;
padding: 10px 0;
background: #991188;
color: #fff;
}
.dajianshi {
margin: 5px auto 0;
border: 1px solid #ccc;
width: 980px;
height: 490px;
background-color: #eee;
}
</style>
参考资料:
https://www.zhangxinxu.com/wordpress/2018/02/canvas-text-break-line-letter-spacing-vertical/