canvas html scaling
how does the canvas react to html scaling?
by rob Davis
HTML
<div id="container">
<div>
<canvas id="starfield" />
</div>
<div>
<canvas id="tunnel" />
</div>
</div>
<input type="button" id="btn-shrink" value="shrink"/>
<input type="button" id="btn-grow" value="grow"/>
CSS
#container { background-color:yellow;
width:500px;
height:500px;
position:relative;
}
#tunnel {position:absolute; top:0px; left:0px; width:100%; height:100%; }
#starfield {position:absolute; top:0px; left:0px; width:100%; height:100%; }
JavaScript
setStarfield('starfield');
setTunnel('tunnel');
$('#btn-shrink').click(function() {
$('#container').animate({
width: "100px",
height: "100px"
}, "slow");
});
$('#btn-grow').click(function() {
$('#container').animate({
width: "500px",
height: "500px"
});
});
function setTunnel(id) {
var canvas = document.getElementById(id);
var context = canvas.getContext('2d');
var width=400;
var height=400;
setCanvasSize(canvas, width, height);
//clearCanvas(canvas, context, '#000');
//drawDot(context, 200, 200, 200, '#00f');
var gradient = context.createRadialGradient(1, 1, 0, 1, 1, 1);
gradient.addColorStop(0.5,'rgba(255,255,0,0.0)');
gradient.addColorStop(1.0,'rgba(0,255, 255,1.0)');
drawEllipse(context, 200, 200, 200, 200, gradient);
}
function drawEllipse(context, cx, cy, rx, ry, fill){
context.save();
context.beginPath();
context.translate(cx-rx, cy-ry);
context.scale(rx, ry);
var ellipseFill;
if (typeof(fill)==='function') {
ellipseFill=fill(context);
} else {
ellipseFill=fill;
}
context.arc(1, 1, 1, 0, 2 * Math.PI, false);
context.fillStyle = ellipseFill;
context.fill();
context.closePath();
context.restore();
}
function setStarfield(id) {
var canvas = document.getElementById(id);
var context = canvas.getContext('2d');
var width=400;
var height=400;
var maxStars=1000;
setCanvasSize(canvas, width, height);
clearCanvas(canvas, context, "#000");
addStars(context, canvas.width, canvas.height, maxStars);
}
function setCanvasSize(canvas, width, height) {
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
}
function clearCanvas(canvas, context, style) {
context.fillStyle = style;
context.fillRect(0,0,canvas.width, canvas.height);
}
function addStars(context, width, height, maxStars) {
for (var i=0;i<maxStars;i++) {
...