我正在尝试绘制一个红色圆圈,鼠标点击但没有绘制任何内容。我可以按照我点击的x,y坐标。如果我在arc方法中为x,y设置常量值,则会显示一个圆。我做错了什么?
var currColor = "#FF0000";
var currSize = 20;
window.onload = function() {
var theCanvas = document.getElementById('my_canvas');
theCanvas.addEventListener("click", CircleOnClick, false);
}
function Cell(row, column) {
this.row = row;
this.column = column;
}
function getCursorPosition(e) {
var x;
var y;
if (e.pageX != undefined && e.pageY != undefined) {
x = e.pageX;
y = e.pageY;
}
else {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
var cell = new Cell(x, y);
return cell;
}
function CircleOnClick(e) {
var canvasElement = document.getElementById('my_canvas');
if (canvasElement && canvasElement.getContext) {
var ctx = canvasElement.getContext("2d");
if (ctx) {
var cell = getCursorPosition(e);
var x = parseInt(cell.row);
var y = parseInt(cell.column);
//Start drawing
ctx.fillStyle=currColor;
ctx.beginPath();
console.log("x" + x);
console.log("y" + y);
console.log("Current color" + currColor);
console.log("Current size" + currSize);
ctx.arc(x,y,currSize,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();
}
}
}
答案 0 :(得分:1)
使用fabric.js,这将需要10行:
HTML:
<canvas id="c" width="300" height="300" style="border:1px dotted #ccc"></canvas>
JS:
var canvas = new fabric.Canvas('c', { selection: false });
canvas.observe('mouse:up', function(e) {
var pointer = canvas.getPointer(e.memo.e);
canvas.add(
new fabric.Circle({
radius: 10,
left: pointer.x,
top: pointer.y,
fill: 'red',
selectable: false
}));
});
答案 1 :(得分:0)
您的代码适用于我。您确定HTML canvas
元素具有id="my_canvas"
属性吗?
或者你也可以展示你的HTML代码吗?
如果您在Internet Explorer 9中进行测试,则您的HTML文档必须以<!DOCTYPE html>
开头,除非您启用了开发人员工具(F12),否则您还必须注释掉console.log
行:
ctx.fillStyle=currColor;
ctx.beginPath();
//console.log("x" + x);
//console.log("y" + y);
//console.log("Current color" + currColor);
//console.log("Current size" + currSize);
ctx.arc(x,y,currSize,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();