canvas gotcha

I was learning to use Javascript Canvas recently, but was almost stumped by a little issue with sizing the thing. In Firefox 2 at least it looks like the canvas size needs to be set on the canvas tag. When I applied a width and height with CSS, it just resulted in the whole canvas being scaled up, with obvious artifacts. (Canvas has a default size of 300 × 150).

screen capture of problem in Firefox 2

Here’s an example page to illustrate the problem. The relevant bits of code look like this:

<script type="text/javascript">
function drawCross(canvas) {
	var ctx = canvas.getContext('2d');
	ctx.lineWidth = 2;
	ctx.strokeStyle = '#900';
	ctx.beginPath();
	ctx.moveTo(0, 0);
	ctx.lineTo(canvas.width, canvas.height);
	ctx.moveTo(0, canvas.height);
	ctx.lineTo(canvas.width, 0);
	ctx.stroke();
}
 
window.onload = function() {
	var c1 = document.getElementById('c1');
	drawCross(c1);
	var c2 = document.getElementById('c2');
	drawCross(c2);
}
</script>
 
<style type="text/css">
canvas {
	border: solid thin black;
}
 
#c1 {
	width: 700px;
	height: 500px;
}
</style>
 
<canvas id="c1">If you can read this, your browser doesn't support &lt;canvas&gt;.</canvas>
 
<canvas id="c2" width="700" height="500">If you can read this, your browser doesn't support &lt;canvas&gt;.</canvas>

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*