Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a filled circle in a canvas on mouseclick

I want to draw a filled (or not filled) circle in a canvas on mouseclick, but I can't get my code to work properly, I've tried pretty much everything!

This is my HTML:

<div id="images"></div>
<canvas style="margin:0;padding:0;position:relative;left:50px;top:50px;" id="imgCanvas" width="250" height="250" onclick="draw(e)"></canvas>

and my current script:

var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");

function createImageOnCanvas(imageId) {
    canvas.style.display = "block";
    document.getElementById("images").style.overflowY = "hidden";
    var img = new Image(300, 300);
    img.src = document.getElementById(imageId).src;
    context.drawImage(img, (0), (0)); //onload....
}

function draw(e) {
    var pos = getMousePos(canvas, e);
    posx = pos.x;
    posy = pos.y;
    context.fillStyle = "#000000";
    context.arc(posx, posy, 50, 0, 2 * Math.PI);
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}

The code works just fine if and only if I remove the "use strict";, but in this assignment I have to make a code that works even with it, which is my problem.

Here is the jsFiddle

like image 746
Davy Karlsson Avatar asked Dec 11 '13 17:12

Davy Karlsson


1 Answers

Solved it myself.

function draw(e) {

    var canvas = document.getElementById("imgCanvas");
    var context = canvas.getContext("2d");
    var rect = canvas.getBoundingClientRect();
    var posx = e.clientX - rect.left;
    var posy = e.clientY - rect.top;

    context.fillStyle = "#000000";
    context.beginPath();
    context.arc(posx, posy, 50, 0, 2 * Math.PI);
    context.fill();
}

This script works fine for me.

like image 153
Davy Karlsson Avatar answered Oct 12 '22 23:10

Davy Karlsson