Reputation: 809
I was trying a script to draw graph paper like grids on the canvas from dive into html5. The result is supposed to draw a mesh with squares of side 10px but i'm getting the size as approximately 20px, and not exact squares.
Here is the code,`
<html>
<head>
<style>
body{
margin: 20px 20px 20px 20px;
}
canvas{
width: 500px;
height: 375px;
border: 1px solid #000;
}
</style>
<script type="text/javascript">
function activate(){
var canvas =document.getElementById("exp");
var context = canvas.getContext("2d");
for (var x=0.5;x<500;x+=10){
context.moveTo(x,0);
context.lineTo(x,375);
console.log(x);
}
for (var y=0.5;y<375;y+=10){
context.moveTo(0,y);
context.lineTo(500,y);
}
context.strokeStyle="#000";
context.stroke();
}
</script>
</head>
<body>
<canvas id="exp"><script type="text/javascript">activate();</script></canvas>
</body
</html>
And this is the output:
while the actual output should be:
Note: i'm not worried about the color difference. what i don't understand is why the space between 2 lines is ~20px(as checked by a measurement tool on firefox) instead of 10px.
Also, on printing the values of x, it gives the right value(i.e. incremented by 10 each time).
Upvotes: 0
Views: 1569
Reputation: 16125
Javascript can calculate for you. Only set the parameters:
html:
<canvas id="exp"></canvas>
js:
function activate(id, xcount, ycount, width, color) {
var canvas = document.getElementById(id);
var context = canvas.getContext("2d");
canvas.width = xcount * width + 1;
canvas.height = ycount * width + 1;
for (var x = 0.5; x < canvas.width; x += width) {
context.moveTo(x, 0);
context.lineTo(x, canvas.height);
}
for (var y = 0.5; y < canvas.height; y += width) {
context.moveTo(0, y);
context.lineTo(canvas.width, y);
}
context.strokeStyle = color;
context.stroke();
}
activate("exp", 37, 50, 10, "#ccc");
Also see this example.
Upvotes: 0
Reputation: 1157
you can not set the canvas' size with css you should set in the DOM's attribute.
<canvas width="100" height="200"></canvas>
Upvotes: 2