Friday, January 27, 2012

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

Merge with the previous post about translate, rotate and scale on context, and how to implement slider using jQuery. We have a demonstration here:





<!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();
}

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>

</center>

</body>
</html>


Check the posts for each individual topic:

No comments:

Post a Comment