将图片插入到canvas中
function convertImageToCanvas(image) {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0);
return canvas;
}
图片加载完成再插入到canvas中
// 图片加载
var imgArray = [
'images/img1.png',
'images/img2.png',
'images/img3.png'
];
var imgNum = imgArray.length;
var imgLoaded = 0;
var imgResultArr = [];
for(var i= 0; i < imgNum; i++){
var img = new Image();
img.crossOrigin = 'anonymous';
img.src = imgArray[i];
imgResultArr.push(img);
img.onload = function(){
imgLoaded++;
if (imgLoaded === imgNum){
ctx.drawImage(imgResultArr[0], 0, 0, myCanvas.width, myCanvas.height); //绘制图片1
ctx.drawImage(imgResultArr[1], 60, 390, 435, 435); //绘制图片2
ctx.drawImage(imgResultArr[2], 516, 390, 435, 435) //绘制图片3
}
}
}
解决图片跨域问题
img.crossOrigin = '*';//解决跨域问题,需在服务器端运行,也可为 anonymous
将canvas转成图片
// 将canvas转换成PNG图片
var canvas = document.getElementById("mycanvas");
var img = canvas.toDataURL("image/png");
// 可以像这样插入到页面中,得到图片
document.write('![]('+img+')');
附带解决canvas文字无法换行
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#E992B9";
ctx.lineWidth=1;
var str = "假如生活欺骗了你,请不要悲伤!thank you!"
var lineWidth = 0;
var canvasWidth = c.width;//计算canvas的宽度
var initHeight=15;//绘制字体距离canvas顶部初始的高度
var lastSubStrIndex= 0; //每次开始截取的字符串的索引
for(let i=0;i<str.length;i++){
lineWidth+=ctx.measureText(str[i]).width;
if(lineWidth>canvasWidth){
ctx.fillText(str.substring(lastSubStrIndex,i),0,initHeight);//绘制截取部分
initHeight+=20;//20为字体的高度
lineWidth=0;
lastSubStrIndex=i;
}
if(i==str.length-1){//绘制剩余部分
ctx.fillText(str.substring(lastSubStrIndex,i+1),0,initHeight);
}
}
参考原文
获取设备pixel-ratio
var ctx = myCanvas.getContext('2d');
// 获取设备的 pixel ratio
var getPixelRatio = function(context) {
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
};
var ratio = getPixelRatio(ctx);
相关参考
canvas图片问题浅析
Capture HTML Canvas as gif/jpg/png/pdf?