Sunday, January 29, 2012

HTML5: Capture Canvas using CANVAS.toDataURL()

The function CANVAS.toDataURL() returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element.

Example:
HTML5: Capture Canvas using CANVAS.toDataURL()
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

<script type="text/javascript">
var canvas;
var context;

function loadcanvas(){
canvas = document.getElementById("mycanvas");
context = canvas.getContext("2d");
sliderOnChange(); //Draw the default position
}

function sliderOnChange() {

var varTranslate = document.getElementById("slTranslate").value;
var varRotate = document.getElementById("slRotate").value;
var varScale = document.getElementById("slScale").value;

clearCanvas();
doTransform(varTranslate, varRotate, varScale);
drawSomething();

var btnCaptureCanvas = document.getElementById("capturecanvas");
btnCaptureCanvas.onclick = btnCaptureCanvasListener;

function btnCaptureCanvasListener(){
window.open(canvas.toDataURL(), "canvasImage",
"left=0," + "top=0," + "width=" + mycanvas.width + "," + "height=" + mycanvas.height);
}
}

function doTransform(vTranslate, vRotate, vScale){
context.setTransform(1,0,0,1,0,0); //identity matrix
context.translate(vTranslate, 0);
var angle = vRotate * Math.PI/180; //angle in radians
context.rotate(angle);
context.scale(vScale, vScale); //x scale, y scale
}

function drawSomething(){
context.fillStyle = "#000000";
context.fillRect(0, 0, 100, 100); //( X, Y, WIDTH, HEIGHT)
}

function clearCanvas(){
context.setTransform(1,0,0,1,0,0); //identity matrix
context.translate(0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
}

</script>

</head>
<body onload="loadcanvas();">
<center>
<canvas id="mycanvas" style="border: 5px solid;" width="400" height="250">
Sorry! Your browser doesn't support Canvas.
</canvas>
<div>
Translate
<input id="slTranslate" type="range"
min="0" max="400" value="0"?
onChange="sliderOnChange()"
step="1"/>
Rotate
<input id="slRotate" type="range"
min="0" max="360" value="0"?
onChange="sliderOnChange()" step="1"/>
Scale
<input id="slScale" type="range"
min="0.1" max="2" value="1"?
onChange="sliderOnChange()" step="0.1"/>
</div>
<input type="button" id="capturecanvas" value="Capture Canvas">
</center>

</body>
</html>

No comments:

Post a Comment