解决canvas 绘图不清晰:参考链接
canvas绘文字:参考链接
export default class ShareMapInApp extends Component {
constructor(props) {
super(props);
// 创建一个 ref 来存 储 canvas 的 DOM 元素
this.canvas = React.createRef();
}
componentDidMount() {
this.drawPhoto();
}
drawPhoto = () => {
const title = lodash.get(this.props.basicData, 'name');
const intro = lodash.get(this.props.basicData, 'intro', '');
const that = this;
const canvas = this.canvas.current; //获取当前真实canvasDOM
let context = canvas.getContext('2d'); //创建画布
let ratio = this.getPixelRatio(context) //获取设备的像素比
canvas.width = 218 * ratio;
canvas.height = 175 * ratio;
var img = new Image(); // 创建一个<img>元素
img.src = require('../Images/img_project_share@3x.png'); // 设置图片源地址
// 设置可跨域 不然浏览器会报错Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function() {
// 图片
context.drawImage(img, 0, 0, 218 * ratio, 175 * ratio);
// 项目名称
context.font = `normal bold ${18 * ratio}px PingFangSC-Medium`;
context.textBaseline = 'top';
context.fillStyle = '#FFFFFF';
context.fillText(title, 20 * ratio, 35 * ratio);
// 简介
var text = intro;
var lineW = 178 * ratio; //单行文字行宽
var lineH = 18 * ratio; //单行文字行高
var x = 20 * ratio;
var y = 65 * ratio;
context.font = `${12 * ratio}px PingFangSC-Medium`;
context.globalAlpha = 0.6;
context.fillStyle = '#FFFFFF';
that.canvasWraptitleText(context, text, x, y, lineW, lineH, 2);
let imgBase64 = canvas.toDataURL('image/png', 1);
that.props.setData(imgBase64)
console.log(imgBase64,'imgBase64')
context.save(); // 保存当前画布内容
// let file = that.dataURLtoFile(imgBase64, 'jpg'); // 将base转为file对象
// that.uploadFile(file); // 上传文件
};
};
// 上传文件
uploadFile = file => {
const { basicData } = this.props;
const uploadData = {
partner_id: 'wap'
};
uploadData['param.file'] = file;
fetchGateway('/assist/oss/file/uploadForWeb')
.formData(uploadData)
.post()
.json(res => {
const { code, data } = res;
if (code === 0) {
setHeader({
visibility: true,
buttons: [
{
type: 'icon',
iconLocal: 'shareIcon',
callback: () => {
clickShareHandler(basicData, data.ossUrl);
}
}
]
});
} else {
}
})
.catch(() => {});
};
/**
* 绘制文字自动换行
* @param canvas 当前的canvas
* @param text: 文本
* @param Number x , y 绘制的坐标
* @param Number maxWigth 绘制文字的宽度
* @param Number lineHeight 行高
* @param Number maxRowNum 最大行数
*/
canvasWraptitleText = (
canvas,
text,
x,
y,
maxWidth,
lineHeight,
maxRowNum
) => {
if (
typeof text != 'string' ||
typeof x != 'number' ||
typeof y != 'number'
) {
return;
}
// 字符分隔为数组
var arrText = text.split('');
var line = '';
var rowNum = 1;
for (var n = 0; n < arrText.length; n++) {
var testLine = line + arrText[n];
var metrics = canvas.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
if (rowNum >= maxRowNum) {
var arrLine = testLine.split('');
arrLine.splice(-2);
var newTestLine = arrLine.join('');
newTestLine += '...';
canvas.fillText(newTestLine, x, y);
return;
}
canvas.fillText(line, x, y);
line = arrText[n];
y += lineHeight;
rowNum += 1;
} else {
line = testLine;
}
}
canvas.fillText(line, x, y);
};
// 将base转为file对象
dataURLtoFile = (urlData, fileName) => {
var bytes = window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte
var mime = urlData.split(',')[0].match(/:(.*?);/)[1];
//处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new File([ab], fileName, { type: mime });
};
//获取设备的像素比
getPixelRatio=(context)=>{
let backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
}
render() {
return (
<div className="kr-project-detail-sharePic">
<canvas ref={this.canvas} style={{width:'218px',height:'175px'}}></canvas>
</div>
);
}
}