5

I have a yellow canvas inside of which I draw a red rectangle. But, I noticed an interesting effect--the two sides of the rectangle that are on the border have very defined edges, while the two sides of the rectangle that are inside of the yellow canvas are "softened" or "blurred".

This is what I have now: interesting rectangle

My HTML:

<canvas id="myCanvas"> 
</canvas>

Javascript:

var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);

CSS:

#myCanvas {
    background-color:#FFFF00;
    width:1000px;
    height:600px;
    border: none;
    margin-left:auto;
    margin-right:auto;
}

JSFIDDLE

Why does this happen? And how can I make all four sides of the rectangle very exact and defined? Thank you.

416E64726577
  • 2,214
  • 2
  • 23
  • 47
  • 1
    Removing all CSS makes the blur go away, still confused about why its being blurred in the first place. Good luck! – bottens Apr 08 '14 at 20:01
  • 1
    Anti-aliasing, possibly? See http://stackoverflow.com/questions/195262/can-i-turn-off-antialiasing-on-an-html-canvas-element. – dgvid Apr 08 '14 at 20:03

5 Answers5

9

You should set canvas size like this:

<canvas id="myCanvas" width="1000" height="600"></canvas>

here's the demo

or from javascript:

var canvas = document.getElementById("myCanvas");
canvas.width  = 1000;
canvas.height =  600;

setting size from CSS just scales the canvas which is not what you want!

aneelkkhatri
  • 404
  • 3
  • 10
2

Your CSS is streching your canvas, rather than defining the size of it which causes it to blur. Define your canvas size in the HTML as aneelkkhatri did, or you can define it in your Javascript, see the jsfiddle below.

http://jsfiddle.net/S6vmh/5/

var canvas=document.getElementById("myCanvas");
canvas.width  = 1000;
canvas.height = 600;

var ctx=canvas.getContext("2d");
ctx.wdith=1000;
ctx.fillStyle="#FF0000";
ctx.fillRect(1,1,150,75);
Adam
  • 4,445
  • 1
  • 31
  • 49
2

For anyone who has this issue when doing a dynamic resizing of the canvas, try changing the imageSmoothing parameter to false

context = canvas.getContext("2d");
context.imageSmoothingEnabled = false;
JPrier
  • 21
  • 1
1

Probably it is scaled from some size. Update: it is scaled from default 300x150 (canvas on mdn)

Try setting width height directly on canvas element.

<canvas id="myCanvas" width="400" height="200"></canvas>

and don't resize it with CSS

#myCanvas {
  background-color:#FFFF00;
  border: none;
  margin-left:auto;
  margin-right:auto;
}

http://jsfiddle.net/T3yU2/

jodator
  • 2,445
  • 16
  • 29
0

Also make sure you don't set the canvas opacity in CSS, in my case this resulted in blurriness. Moving to RGBA on fillStyle fixed it.