2
votes

My pen: http://codepen.io/anon/pen/mBliE

The orange css div with the same orange background and the same black border looks sharp and clean.

The orange rectangle drawn in a canvas looks blurry/distorted.

Why is there a difference? I do not set the canvas height/width with a css style which is a

beginner failure I have heard ;-)

How can I make my canvas sharp looking like css?

<canvas id="mycanvas" height="200" width="400"></canvas>
<div></div>

div{
  border:black 2px solid;
  height:198px;
  width:50px;
  background:orange;
  display:inline-block;
}

canvas {   
    background: red;
}

$(document).ready(function() {

  var canvas = document.getElementById("mycanvas");
  var context = canvas.getContext("2d");
  context.save(); 
  context.lineWidth = 1;

  context.fillStyle = "orange";
  context.fillRect(348, 1, 50, 198);

  context.strokeStyle = "black";
  context.strokeRect(348, 1, 50, 198);

  context.fill();    
  context.restore();

});
2
I moved the rectangles around a bit and they look the same to me. codepen.io/anon/pen/lDEqurfoo

2 Answers

0
votes

You could just play a little bit with you line width:

$(document).ready(function() {

  var canvas = document.getElementById("mycanvas");
  var context = canvas.getContext("2d");
  context.save(); 
  context.lineWidth = 2;

  context.fillStyle = "orange";
  context.fillRect(350, 1, 50, 198);


  context.strokeStyle = "black";
  context.strokeRect(349, 1, 50, 198);

  context.fill();    
  context.restore();

});

CodePen

0
votes

It looks like the stroke is centered on the canvas edges and not located inside or outside, and is set to two px in width as a minimum. By setting the stroke to two - context.lineWidth = 2; - the line gets sharper. Maybe you could somehow move the stroke outside or insede the canvas...

as Ken mentioned...