需求
將canvas轉化爲base64格式的png圖片
實現
<body>
<canvas id="drawing" width=" 200" height="200">A drawing of something.</canvas>
<script>
var drawing = document.getElementById("drawing");
//確定瀏覽器支持<canvas>元素
if (drawing.getContext){
// 獲取畫布
var context = drawing.getContext("2d");
// 畫一個紅色矩形
context.fillStyle="#FF0000";
context.fillRect(0,0,150,150);
//取得圖像的數據 URI
var imgURI = drawing.toDataURL("image/png");
// 創建img元素
var image = document.createElement("img");
// 設置img元素的src
image.src = imgURI;
// 將img元素掛在到dom中
document.body.appendChild(image);
}
</script>
</body>