简体   繁体   English

绘制到html画布中的png图像质量很差

[英]Poor quality of png images drawn into html canvas

I am trying to draw png image into the canvas, but the quality is really poor. 我试图将png图像绘制到画布中,但质量非常差。 I am doing that using the drawImage method: 我正在使用drawImage方法:

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. 这是一个例子的jfiddle。

在此输入图像描述

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. 主要错误是您没有指定canvas元素的大小 - 您只是指定元素本身的CSS大小,这意味着画布上下文将使用默认大小300 x 150像素。

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. 这会导致您显示的图像首先缩小到300 x 150,然后通过CSS缩小到您想要的尺寸(但没有),这会产生模糊的外观。

Solution

To fix you need to specifically set the size on the canvas element (in CSS pixels) and not use a CSS rule: 要解决此问题,您需要专门设置canvas元素的大小(以CSS像素为单位),而不是使用CSS规则:

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

And set them on the canvas element directly as properties and not as CSS: 并将它们直接设置在canvas元素上作为属性而不是CSS:

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

You can optionally set them using JavaScript 您可以选择使用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. 后者可以帮助你调试这个问题 - 如果你把它们排除在外,你会看到在这种情况下绘制的图像非常大,表明画布没有正确的大小设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM