I am trying to draw a 300dpi image to a canvas object but in Chrome it shows in very poor quality. When I used the below code, it did not improve but that was because devicePixelRatio
was the same as backingStoreRatio
(both were 1
).
I then tried to force some ratio changes and found the following:
- if I changed
ratio
to be2
and forced the scaling code to run, then it draws to the canvas in a better resolution. - If I changed
ratio
to anything greater than2
(e.g.3
,4
,5
,6
, etc) then it had poor resolution!
This was all done on a desktop computer.
How can I ensure the canvas draws with a high resolution?
(Code from: http://www.html5rocks.com/en/tutorials/canvas/hidpi/ )
/**
* Writes an image into a canvas taking into
* account the backing store pixel ratio and
* the device pixel ratio.
*
* @author Paul Lewis
* @param {Object} opts The params for drawing an image to the canvas
*/
function drawImage(opts) {
if(!opts.canvas) {
throw("A canvas is required");
}
if(!opts.image) {
throw("Image is required");
}
// get the canvas and context
var canvas = opts.canvas,
context = canvas.getContext('2d'),
image = opts.image,
// now default all the dimension info
srcx = opts.srcx || 0,
srcy = opts.srcy || 0,
srcw = opts.srcw || image.naturalWidth,
srch = opts.srch || image.naturalHeight,
desx = opts.desx || srcx,
desy = opts.desy || srcy,
desw = opts.desw || srcw,
desh = opts.desh || srch,
auto = opts.auto,
// finally query the various pixel ratios
devicePixelRatio = window.devicePixelRatio || 1,
backingStoreRatio = context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1,
ratio = devicePixelRatio / backingStoreRatio;
// ensure we have a value set for auto.
// If auto is set to false then we
// will simply not upscale the canvas
// and the default behaviour will be maintained
if (typeof auto === 'undefined') {
auto = true;
}
// upscale the canvas if the two ratios don't match
if (auto && devicePixelRatio !== backingStoreRatio) {
var oldWidth = canvas.width;
var oldHeight = canvas.height;
canvas.width = oldWidth * ratio;
canvas.height = oldHeight * ratio;
canvas.style.width = oldWidth + 'px';
canvas.style.height = oldHeight + 'px';
// now scale the context to counter
// the fact that we've manually scaled
// our canvas element
context.scale(ratio, ratio);
}
context.drawImage(pic, srcx, srcy, srcw, srch, desx, desy, desw, desh);
}
Making only the below changes results in high resolution canvas images (why?):
//WE FORCE RATIO TO BE 2
ratio = 2;
//WE FORCE IT TO UPSCALE (event though they're equal)
if (auto && devicePixelRatio === backingStoreRatio) {
If we change the above to be a ratio of 3
, it is no longer high resolution!
EDIT: One additional observation - even with the 2x ratio, while it is noticeably better resolution, it's still not as sharp as showing the image in an img
tag)