How To Draw A Simple Ruler With JavaScript?
Solution 1:
Couple issues going on.
Take a look at http://diveintohtml5.info/canvas.html - it goes over how to avoid blurry lines (start lines at .5 pixels) and talks about the canvas size (don't do it via css).
As an example take a look here: http://jsfiddle.net/QdBd7/2/
Changes:
This fixes the odd line width:
drawOnCanvas(Math.floor(topPos)+.5)
Added missing begin path:
ctx.beginPath();
Change to set canvas size on load:
function resizeCanvas(){
c.width = document.body.clientWidth - 5, // 5 is from jsfiddle frame
c.height = document.body.clientHeight - 5;
}
Even with these changes you still notice slight variations, I wan't to point this to: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
But I don't have any solutions (since the ppm might end up at some odd y value like 75.812315 -- it'll be .3 pixels off...) as you draw more you could adjust for the variations somehow but it gets even more tricky as the floating point errors start to come in.
Hope that gets you started.
Solution 2:
var cmm=15
var countCm=0
var c = document.getElementById("myCanvas");
var ctx= c.getContext("2d");
ctx.lineWidth = 1;
ctx.fillRect(0,0,30,250);
function drawOnCanvas(y){
ctx.beginPath();
ctx.moveTo(0,y);
ctx.lineTo(cmm,y);
ctx.stroke();
}
function drawRuler(){
var ppm = 8.602150744349842,
count = Math.floor(c.height / ppm);
for(var i=0; i<count; i++){
if(countCm==4){cmm=15;countCm=0}else{cmm=4;countCm++}
var topPos = (5 + i*ppm);
drawOnCanvas(Math.floor(topPos)+.5);
};
}
function resizeCanvas(){
c.width = document.body.clientWidth - 5,
c.height = document.body.clientHeight - 5;
}
resizeCanvas();
drawRuler();
Post a Comment for "How To Draw A Simple Ruler With JavaScript?"