这是代码。
(function() {
// Creates a new canvas element and appends it as a child
// to the parent element, and returns the reference to
// the newly created canvas element
function createCanvas(parent, width, height) {
var canvas = {};
canvas.node = document.createElement('canvas');
canvas.context = canvas.node.getContext('2d');
canvas.node.width = width || 100;
canvas.node.height = height || 100;
parent.appendChild(canvas.node);
return canvas;
}
function init(container, width, height, fillColor) {
var canvas = createCanvas(container, width, height);
var ctx = canvas.context;
// define a custom fillCircle method
ctx.fillCircle = function(x, y, radius, fillColor) {
this.fillStyle = fillColor;
this.beginPath();
this.moveTo(x, y);
this.arc(x, y, radius, 0, Math.PI * 3, false);
this.fill();
};
ctx.clearTo = function(fillColor) {
ctx.fillStyle = fillColor;
ctx.fillRect(0, 0, width, height);
};
ctx.clearTo(fillColor || "#ddd");
// bind mouse events
canvas.node.onmousemove = function(e) {
if (!canvas.isDrawing) {
return;
}
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var radius = 20; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
};
canvas.node.onmousedown = function(e) {
canvas.isDrawing = true;
};
canvas.node.onmouseup = function(e) {
canvas.isDrawing = false;
};
}
var container = document.getElementById('canvas');
init(container, 274, 308, '#ddd');
})();
答案 0 :(得分:0)
您的画布仅侦听鼠标事件。您也应该绑定浏览器触摸事件。取决于移动浏览器它的方式,它可能有点不同。以下是一些您可以从中开始的好资源:
答案 1 :(得分:0)
您正在寻找touchstart
(here)和touchend
(here)事件。
请注意,这些的pageX和pageY可能有点棘手。
这是我过去用来在浏览器中获取这些坐标的函数 - 甚至是移动版Safari。如果你遇到问题,只需将事件传递给它就可以更可靠地获得坐标。
function getPageXAndY(evt) {
var pageX = evt.pageX;
if (!pageX) {
if (evt.originalEvent && evt.originalEvent.touches) {
pageX = evt.originalEvent.touches[0].pageX;
}
else if (evt.touches && evt.touches.length > 0) {
pageX = evt.touches[0].pageX;
}
}
var pageY = evt.pageY;
if (!pageY) {
if (evt.originalEvent && evt.originalEvent.touches) {
pageY = evt.originalEvent.touches[0].pageY;
}
else if (evt.touches && evt.touches.length > 0) {
pageY = evt.touches[0].pageY;
}
}
return [pageX, pageY];
};
叫做:
canvas.node.ontouchend = function(e) {
pageCoords = getPageXAndY(e); // returns [pageXVal, pageYVal]
...
}