Happy
Happy

Reputation: 86

blurred text when a canvas is placed on top of another canvas

I want to display the mouse's x position on canvas as mouse moves. Can someone please tell why the text is so big and blurry and also is there any way to achieve the transparency between these two canvases

<body style="margin: 0; padding: 0; height: 100%; width: 100%; overflow: hidden;">
  <canvas id="myCanvas" style="display: block; height: 100%; width: 100%;">
            Your browser does not support the HTML5 canvas tag.</canvas>  <canvas id="temp">
            Your browser does not support the HTML5 canvas tag.</canvas>
    <script type="text/javascript">

        var c = document.getElementById("myCanvas");

        var ctx = c.getContext("2d");

        var hgap = 0;
        var vgap = 0;
        var rows, cols;
        var annotation_x = 1;
        var row = 0; var col = 0;
        //ctx.font = "14px Arial";

        var t = document.getElementById("temp");
        tctx = t.getContext("2d");
        // tctx.lineWidth = 10;
        tctx.lineJoin = 'round';
        tctx.lineCap = 'round';
        tctx.strokStyle = 'red';


        var mouse = { x: 0, y: 0 };
        c.addEventListener('mousemove', function (evt) {
        //    tctx.clearRect(0, 0, c.width, c.height);
            ctx.clearRect(0, 0, c.width, c.height);
            mouse.x = evt.pageX;
            mouse.y = evt.pageY;
            ctx.fillText(mouse.x, 10, 10);

        }, false);



    </script>
</body>

Upvotes: 0

Views: 221

Answers (2)

Oriol
Oriol

Reputation: 288120

The problem isn't due to having two canvas.

The problem is that you scale your canvas using CSS, but you don't modify its number of pixels (height and width attributes). Then, the result is blurry.

If you don't scale it with CSS, the result is fine: Demo

Alternatively, you can try using image-rendering CSS property (e.g. crisp-edges, demo)

You can also modify height and width attributes when the browser is resized (resize event), and redraw the canvas.

Upvotes: 2

thykka
thykka

Reputation: 550

<canvas id="myCanvas" style="display: block; height: 100%; width: 100%;">

^ You shouldn't scale a canvas element with CSS unless you want it's contents to be interpolated. Consider a 300x125px image, which you've scaled to the width and height of the browser window - the image will become blurry.

If you wish to have a full-screen canvas you need to scale it with JS:

var c = document.getElementById("myCanvas");
c.width = window.innerWidth;
c.height = window.innerHeight;

..or with HTML:

<canvas width="1920" height="1080"></canvas>

Upvotes: 2

Related Questions