3

This MDN article (citing this blog post) teaches how to render HTML content to a canvas. I've implemented it in my project and it works.

But on "retina" displays, it draws to the canvas at only half of the full resolution that the display supports. For example, if I have a canvas on which I render the HTML string "Hello" and next to the canvas I put a <span>Hello</span>, the latter (rendered by the browser the usual way) is smoother and crisper than the former (rendered as HTML onto a canvas, using the technique in the links above, which uses an SVG and an Image).

I believe there's a way to detect retina displays, so that I know when higher resolution is needed, given in this source code. But when I detect that I'm on a retina display, my question is:

Is there a method that renders HTML to the canvas at the full retina resolution?

1 Answer 1

3

Look at this post

var image   = new Image();
var ratio   = window.devicePixelRatio || 1;
var canvas  = document.querySelector("canvas");
var context = canvas.getContext("2d");

// 1. Ensure the element size stays the same.
canvas.style.width  = canvas.width + "px";
canvas.style.height = canvas.height + "px";

// 2. Increase the canvas dimensions by the pixel ratio.
canvas.width  *= ratio;
canvas.height *= ratio;

image.onload = function() {
  // 3. Scale the context by the pixel ratio.
  context.scale(ratio, ratio);
  context.drawImage(image, 0, 0);
};
image.src = "/path/to/image.svg";

I've tried it - it works!

0

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.