问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/19703450/poor-quality-of-png-images-drawn-into-html-canvas