Canvas How to - Save image to data URL base 64 string








Question

We would like to know how to save image to data URL base 64 string.

Answer


<!--   w w w . j  a v a  2  s  .c o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<style type='text/css'>
canvas {
  border: 1px solid red;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        ctx.fillRect(25, 25, 100, 100);
        var dataURL;
        $("#save").click(function () {
            dataURL = canvas.toDataURL();
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        });
        $("#reload").click(function () {
            var image = new Image();
            image.onload = function () {
                ctx.drawImage(image, 0, 0);
            }
            image.src = dataURL;
        });
});
</script>
</head>
<body>
  <canvas id="canvas" width=300 height=300></canvas>
  <button id="save">Save</button>
  <button id="reload">Reload</button>
</body>
</html>

The code above is rendered as follows: