鼠标点击在画布上画一个圆圈

2022-01-17 00:00:00 javascript html5-canvas

我想在鼠标单击时在画布上绘制一个实心(或非实心)圆圈,但我的代码无法正常工作,我已经尝试了几乎所有方法!

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!

这是我的 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>

和我当前的脚本:

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
    };
}

我认为我的问题在于 function draw(e),尽管我对那部分很有信心.

I think my problem is with function draw(e), even though I feel pretty confident about that part.

这里是 jsFiddle

推荐答案

我已经分叉并更新了你的小提琴以制作一个工作示例:http://jsfiddle.net/ankr/ds9s7/161/

I have forked and updated your fiddle to make a working example: http://jsfiddle.net/ankr/ds9s7/161/

除了错误地引用了事件——正如其他人所说——你在绘画时也没有开始或结束你的路径.添加了 context.beginPath()context.fill() 调用

Besides referencing the event incorrectly - as stated by others - you also did not begin nor end your path when drawing. Added context.beginPath() and context.fill() calls

这是相关的JS代码

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

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

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

相关文章