canvas创建/图片和base64互转

部分参考自http://blog.csdn.net/renfufei/article/details/9855519

创建canvas

var canvas = document.createElement('canvas'); 
canvas.id     = "CursorLayer"; 
canvas.width  = 1224; 
canvas.height = 768; 
canvas.style.zIndex   = 8; 
canvas.style.position = "absolute"; 
canvas.style.border   = "1px solid";
document.body.appendChild(canvas);

图片转base64

// 把image 转换为 canvas对象  
function convertImageToCanvas(image) {  
    // 创建canvas DOM元素,并设置其宽高和图片一样   
    var canvas = document.createElement("canvas");  
    canvas.width = image.width;  
    canvas.height = image.height;  
    // 坐标(0,0) 表示从此处开始绘制,相当于偏移。  
    canvas.getContext("2d").drawImage(image, 0, 0);  
  
    return canvas;  
}

 

base64转图片

var fin = new Image();
    fin.src =  canvas.toDataURL("image/jpg");
document.body.appendChild(fin);