Canvas Transformations 1
Translating, rotating and scaling using functions
by Francisco Maria Calisto
HTML
<div class="cell">
<h1>Original</h1>
<canvas id="canvas" width="150" height="150"></canvas>
<button onclick="original();">Draw</button>
<button onclick="rotate();">Draw rotated</button>
</div>
<div class="cell">
<h1>Translated</h1>
<canvas id="canvas2" width="150" height="150"></canvas>
<button onclick="translated();">Draw</button>
<button onclick="rotate2();">Draw rotated</button>
<button onclick="rotate3();">Draw rotated 2</button>
</div>
<div class="cell">
<h1>Scaling</h1>
<canvas id="canvas3" width="150" height="150"></canvas>
<button onclick="scale();">Draw</button>
<button onclick="scale2();">Scale</button>
</div>
CSS
canvas {
border: 1px red solid;
}
.cell {
width: 160px;
display: inline-block;
vertical-align:top
}
.cell button {
width: 150px;
}
JavaScript
function original() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.fillRect(0,0,70,70);
}
function translated() {
var ctx = document.getElementById('canvas2').getContext('2d');
ctx.translate(40, 40);
ctx.fillRect(0,0,70,70);
}
function rotate() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.rotate(Math.PI/8);
ctx.fillStyle = "#0095DD";
ctx.fillRect(0,0,70,70);
}
function rotate3() {
var ctx = document.getElementById('canvas2').getContext('2d');
ctx.translate(35, 35);
ctx.rotate(Math.PI/8);
ctx.translate(-35, -35);
ctx.fillStyle = "#0095DD";
ctx.fillRect(0,0,70,70);
}
function rotate2() {
var ctx = document.getElementById('canvas2').getContext('2d');
ctx.rotate(Math.PI/8);
ctx.fillStyle = "#0095DD";
ctx.fillRect(0,0,70,70);
}
function scale() {
var ctx = document.getElementById('canvas3').getContext('2d');
ctx.translate(40, 40);
ctx.fillRect(0,0,70,70);
}
function scale2() {
var ctx = document.getElementById('canvas3').getContext('2d');
ctx.scale(1.3, 0.3);
ctx.fillStyle = "#0095DD";
ctx.fillRect(0,0,70,70);
}