[英]How to create image on mouse click event using html5 and javascript
I an newbie in html5, I want to create an a dot like image on click event. 我是html5的新手,我想在点击事件中创建一个像图片一样的点。 I try to use context but unfortunately not working. 我尝试使用上下文,但不幸的是无法正常工作。 The code that i am using is 我正在使用的代码是
document.addEventListener("DOMContentLoaded", init, false);
function init()
{
var canvas = document.getElementById("options");
canvas.addEventListener("mousedown", getPosition, false);
}
function getPosition(event)
{
var x = new Number();
var y = new Number();
var canvas = document.getElementById("options");
if (event.x != undefined && event.y != undefined)
{
x = event.x;
y = event.y;
}
else // Firefox method to get the position
{
x = event.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
alert("x: " + x + " y: " + y);
var b_canvas = document.getElementById("b");
var b_context = b_canvas.getContext("2d");
b_context.fillRect(50, 25, 150, 100);
Please suggest where I am doing mistake. 请指出我在哪里做错了。 Give your suggestions 给你建议
Not sure if that's the problem, but to draw a dot on canvas, you can start a path, draw a completely closed arc (from 0 rad to 2pi rad) and fill that: 不确定这是否是问题,但是要在画布上画一个点,您可以开始一条路径,绘制一个完全闭合的弧(从0 rad到2pi rad),并填充:
b_context.beginPath();
b_context.arc(x, y, 5 , 0, 2 * Math.PI,true);
b_context.fillStyle = "blue";
b_context.fill();
Further it is important to set width and height directly on canvas and not in css to prevent distortion. 此外,重要的是直接在画布上而不是在CSS中设置宽度和高度,以防止变形。 (just found that out myself ;) ) Complete example fiddle: http://jsfiddle.net/wHsMJ/ (click inside the rectangle on the right to test) (刚刚发现自己;))完整的示例小提琴: http : //jsfiddle.net/wHsMJ/ (单击右侧的矩形进行测试)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.