Thursday, January 26, 2012

HTML5 Canvas: Move center of canvas using Context.translate()

Example:
HTML5 Canvas: Move center of canvas using Context.translate()
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mobile-Web-App: HTML5 Canvas</title>
<script type="text/javascript">
function loadcanvas(){
var canvas;
var context;

canvas = document.getElementById("mycanvas");
context = canvas.getContext("2d");

drawPath(context, "#000000"); //Draw before translate
transformCanvasCenter(context, canvas.width/2, canvas.height/2);
drawPath(context, "#A0A0A0"); //Draw after translate
}

//Move center of Canvas using Context.translate()
function transformCanvasCenter(c, offx, offy){
c.setTransform(1,0,0,1,0,0); //identity matrix
c.translate(offx, offy);
}

function drawPath(c, color){

c.fillStyle = color;
c.fillRect(0, 0, 100, 100); //( X, Y, WIDTH, HEIGHT)
}


</script>
</head>
<body onload="loadcanvas();">
<h1>Mobile-Web-App: HTML5 canvas</h1>

<canvas id="mycanvas" style="border: 5px solid;" width="400" height="350">
Sorry! Your browser doesn't support Canvas.
</canvas>
</body>
</html>


Related:
- HTML5 Canvas@((Context.(translate x rotate x scale)) + jQuery Slider)

No comments:

Post a Comment