在鼠标点击中在画布上绘制一个圆圈 [英] Drawing a circle in a canvas on mouseclick

查看:216
本文介绍了在鼠标点击中在画布上绘制一个圆圈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在鼠标点击画布上绘制一个填充(或未填充)的圆圈,但是我无法让我的代码正常工作,我已经尝试了很多东西!

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

我认为我的问题是函数绘制(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
    };
}

这篇关于在鼠标点击中在画布上绘制一个圆圈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆