Drawing a 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!
这是我的 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
};
}
这篇关于鼠标点击在画布上画一个圆圈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:鼠标点击在画布上画一个圆圈
基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
