首页 > 代码库 > Canvas 生成base64的PNG图片快照,So Amazing!!!

Canvas 生成base64的PNG图片快照,So Amazing!!!

function canvasSupport(){
     return Modernizr.canvas;
}
function callCanvasApps(){
  var canvasOne=document.getElementById("canvasOne");
  //if(!canvasSupport())
      //return;
  var context=canvasOne.getContext("2d");
  context.fillStyle = "#ffffaa";
  context.fillRect(0, 0, 500, 300);
 
  context.fillStyle  = "#000000";
  context.font = "20px Sans-Serif";
  context.textBaseline = "top";
  context.fillText  ("xxx 我稀罕你", 195, 80 );
  console.log(canvasOne.toDataURL());//  这句生成快照,可以将结果直接拷贝放到浏览器的URL里回车看到结果,这个以后做PNG图片似乎不需要美工了么 ,O(∩_∩)O哈哈~
}
if(window.addEventListener){
   window.addEventListener("load",callCanvasApps,false);
}else{
   window.onload=callCanvasApps;
}

如果想生成jpeg图片,可以这样指定类型:canvasOne.toDataURL("image/jpeg"); 其他类型 you must know

至于base64图片的作用 ,大概就是减少request吧

:<img width="40" height="30" src="http://www.mamicode.com/data:image/jpg;base64,/9j/4QMZRXhpZgAASUkqAAgAAAAL...." />

 

.demoImg{ background-image: url("data:image/jpg;base64,/9j/4QMZRXhpZgAASUkqAAgAAAAL...."); }

 

Canvas 生成base64的PNG图片快照,So Amazing!!!