user4227915
user4227915

Reputation:

Rectangle not displaying in canvas when drawing with mouse events

I'm trying to draw a rectangle with mouse events, it seems to work, I've used console.log in all my code to see what is happening, and is all running nice, but the rectangle just dislikes me I think, it doesn't appear!

I can't figure out how to find the mistake!

I only want a direction, thank you for your time.

Fiddle here.

And the code here:

$("body").wrapInner("<canvas id='myCanvas'>");
var canvas = $("#myCanvas").css("cursor", "crosshair");
var context = canvas[0].getContext("2d");
var div = {x:0, y:0};
var draw_rectangle = function(e){
    context.fillRect (
        div.x, div.y,
        (e.pageX - div.x),
        (e.pageY - div.y)
    );
};
context.fillStyle = "#aaf";
canvas.on("mousedown", function(e){
    div.x = e.pageX;
    div.y = e.pageY;
    canvas.on("mousemove", draw_rectangle);
});
canvas.on("mouseup", function(){
    canvas.off("mousemove");
    console.log("Drawed.");
});

Upvotes: 0

Views: 89

Answers (1)

Markai
Markai

Reputation: 2098

The thing is, that the css properties``height and width are problematic with canvas elements, because they stretch your canvas element to fit the given size - stretching the canvas' bitmap. The html properties height and width on the other hand determine the size of your canvas' bitmap.

So, a solution in your case would be, to change your code to the following:

$("body").wrapInner("<canvas id='myCanvas'>");
$('#myCanvas').attr("width", 400);
$('#myCanvas').attr("height", 500);
var canvas = $("#myCanvas").css("cursor", "crosshair");
var context = canvas[0].getContext("2d");
var div = {x:0, y:0};
var draw_rectangle = function(e){
    context.fillRect (
        div.x, div.y,
        (e.pageX - div.x),
        (e.pageY - div.y)
    );
};
context.fillStyle = "#aaf";
canvas.on("mousedown", function(e){
    div.x = e.pageX;
    div.y = e.pageY;
    canvas.on("mousemove", draw_rectangle);
});
canvas.on("mouseup", function(){
    canvas.off("mousemove");
    console.log("Drawed.");
});
canvas {
    background-color: rgba(0, 0, 0, 0.3);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Information Source: Canvas is stretched when using CSS but normal with "width" / "height" properties

Upvotes: 1

Related Questions