这是我正在尝试做的源代码:
Javascript:
window.addEventListener('load', function () {
// get the canvas element and its context
var canvas = document.getElementById('sketchpad');
var context = canvas.getContext('2d');
// create a drawer which tracks touch movements
var drawer = {
isDrawing: false,
touchstart: function (coors) {
context.beginPath();
context.moveTo(coors.x, coors.y);
this.isDrawing = true;
},
touchmove: function (coors) {
if (this.isDrawing) {
context.lineTo(coors.x, coors.y);
context.stroke();
}
},
touchend: function (coors) {
if (this.isDrawing) {
this.touchmove(coors);
this.isDrawing = false;
}
}
};
// create a function to pass touch events and coordinates to drawer
function draw(event) {
// get the touch coordinates
var coors = {
x: event.targetTouches[0].pageX,
y: event.targetTouches[0].pageY
};
// pass the coordinates to the appropriate handler
drawer[event.type](coors);
}
// attach the touchstart, touchmove, touchend event listeners.
canvas.addEventListener('touchstart', draw, false);
canvas.addEventListener('touchmove', draw, false);
canvas.addEventListener('touchend', draw, false);
// prevent elastic scrolling
document.body.addEventListener('touchmove', function (event) {
event.preventDefault();
}, false); // end body.onTouchMove
}, false); // end window.onLoad
HTML:
<body>
<div id="container">
<canvas id="sketchpad" width="400" height="400">Sorry, your browser is not supported.</canvas>
</div>
</body>
CSS:
body {
margin:0;
padding:0;
font-family:Arial;
}
#container {
position:relative;
}
#sketchpad {
border: 1px solid #000;
}
我尝试为鼠标向下/向上/移动添加事件侦听器,但这些似乎不起作用。
或者,如果有人对在计算机和平板电脑上运行的开源画布绘画应用程序有任何建议,我宁愿只使用它。
到目前为止,唯一脱颖而出的是https://github.com/PlayMyCode/SkyBrush但不幸的是它不适用于 android 平板电脑(至少我已经能够尝试的那些)。