Simon Arnold
Simon Arnold

Reputation: 16177

Drawing in canvas become offset

I'm trying to draw into a canvas, but the more I go right, the more offset my drawing become.

Anyone have an idea why?

I have included the relevant code below:

CSS

html,body {
    width:100%;
    height:100%;
    background:rgba(0,0,0,.2);
}
#container {
    position:relative;
    width:700px;
    height:450px;
    background:#fff;
    overflow:hidden;
}
* {
    -webkit-user-select: none;
}
canvas {
    position: absolute;
    top: 0;
    left: 0;
    background: #ccc;
    width: 500px;
    height: 200px;
}

HTML

<div id='adContainer'>
    <canvas></canvas>
</div>

Javascript

var ctx;
var can = $('canvas');

$(document).ready(function() {
    ctx = can[0].getContext('2d');
    ctx.strokeStyle = "rgba(255,0,0,1)";
    ctx.lineWidth = 5;
    ctx.lineCap = 'round';

    can.on("touchstart", function(event) {
        event.preventDefault();
        var e = event.originalEvent;
        if(e.touches.length == 1) {
            var posX = e.touches[0].pageX;
            var posY = e.touches[0].pageY;
            ctx.moveTo(posX, posY);
        }
    });

    can.on("touchmove", function(event) {
        event.preventDefault();
        var e = event.originalEvent;
        if(e.touches.length == 1) {
            var posX = e.touches[0].pageX;
            var posY = e.touches[0].pageY;
            ctx.lineTo(posX, posY);
            ctx.stroke();
        }
    });
});

Demo: http://jsfiddle.net/8Wtf8/

Upvotes: 1

Views: 1430

Answers (1)

user1693593
user1693593

Reputation:

That is because you define the size of the canvas using CSS.

What happens is that when you don't explicitly define the size of the canvas using its width and height attributes the canvas defaults to size 300 x 150.

In your CSS you are then stretching the canvas element (look at it as an image) to 500px etc. - the content of the canvas is still 300 x 150.

You need to set the width and height on the canvas element itself:

<canvas width=500 height=200 id="myCanvas"></canvas>

and remove the definition from the CSS:

canvas {
    position: absolute;
    top: 0;
    left: 0;
    background: #ccc;
    /*width: 500px;
    height: 200px;*/
}

Also notice that background set by CSS will not be part of the canvas content.

Upvotes: 2

Related Questions