Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
61
rated 0 times [  65] [ 4]  / answers: 1 / hits: 38777  / 10 Years ago, wed, december 11, 2013, 12:00:00

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


More From » html

 Answers
16

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.


[#73787] Tuesday, December 10, 2013, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brandensebastiand

Total Points: 323
Total Questions: 115
Total Answers: 106

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;