7

I am trying to draw png image into the canvas, but the quality is really poor. I am doing that using the drawImage method:

src = folder+self.cur+".png";
imageObj.src = src;
imageObj.onload = function() {
    context.clearRect(0, 0, cv, ch), context.drawImage(imageObj, 0, 0, cv, ch)
};

Attached is an original image and the screenshot of the result in the canvas. For now canvas dimensions are the same as the image, so the problem is not caused by the resizing.

Any ideas what is causing this issue and how to solve it? Here is a jfiddle with an example.

enter image description here

2
  • Please show more of the code you're using (a fiddle would be super). You also have a comma (instead of ; ) between clear and draw in the above example, not sure if that's a typo? If no resizing takes place you don't need to provide width and height for the drawImage() method.
    – user1693593
    Oct 31, 2013 at 16:16
  • Here is a jfiddle jsfiddle.net/UffUv/1
    – hjuster
    Nov 1, 2013 at 11:50

1 Answer 1

17

Problem

The main error is that you do not specify the size for the canvas element - you are only specifying the CSS size for the element itself which means the canvas context will work with a default size of 300 x 150 pixels.

This leads to the image you're showing to be scaled down first to 300 x 150, then by CSS up to the size you intent (but aren't having) which creates the blurry look.

Solution

To fix you need to specifically set the size on the canvas element (in CSS pixels) and not use a CSS rule:

#mapCanvas{
    /*width:664px;  Delete these
    height:980px; */
}

And set them on the canvas element directly as properties and not as CSS:

<canvas id='mapCanvas' width=664 height=980></canvas>

You can optionally set them using JavaScript

 mapCanvas.width = 664;   /// use integer values
 mapCanvas.height = 980;

Modified working fiddle here

Then draw the image. As mentioned in the comment above there is also a typo in your code and if you don't re-size your image there is no need to specify width and height of it.

The latter could have helped you debug this problem - if you left them out you would have seen the image being draw very big in this case indicating that the canvas didn't have the proper size set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.