我想在 Canvas 上绘图,用鼠标效果很好,但我必须如何修改代码才能使其在 iPad 或 Nexus 上也能运行?
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width = window.innerWidth;
var height = window.innerHeight;
canvas.height = height;
canvas.width = width;
canvas.addEventListener('mousedown', function(e) {
this.down = true;
this.X = e.pageX ;
this.Y = e.pageY ;
}, 0);
canvas.addEventListener('mouseup', function() {
this.down = false;
}, 0);
canvas.addEventListener('mousemove', function(e) {
if(this.down) {
with(ctx) {
beginPath();
moveTo(this.X, this.Y);
lineTo(e.pageX , e.pageY );
ctx.lineWidth=1;
stroke();
}
this.X = e.pageX ;
this.Y = e.pageY ;
}
}, 0);
最佳答案
这是一个用于绘制鼠标和触摸事件的 HTML 文件。
<!DOCTYPE html>
<html><head><meta charset="utf-8"/><script type='text/javascript'>
window.addEventListener('load', function () {
// get the canvas element and its context
var canvas = document.getElementById('sketchpad');
var context = canvas.getContext('2d');
var isIdle = true;
function drawstart(event) {
context.beginPath();
context.moveTo(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop);
isIdle = false;
}
function drawmove(event) {
if (isIdle) return;
context.lineTo(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop);
context.stroke();
}
function drawend(event) {
if (isIdle) return;
drawmove(event);
isIdle = true;
}
function touchstart(event) { drawstart(event.touches[0]) }
function touchmove(event) { drawmove(event.touches[0]); event.preventDefault(); }
function touchend(event) { drawend(event.changedTouches[0]) }
canvas.addEventListener('touchstart', touchstart, false);
canvas.addEventListener('touchmove', touchmove, false);
canvas.addEventListener('touchend', touchend, false);
canvas.addEventListener('mousedown', drawstart, false);
canvas.addEventListener('mousemove', drawmove, false);
canvas.addEventListener('mouseup', drawend, false);
}, false); // end window.onLoad
</script></head><body encoding='utf8'>
<canvas id='sketchpad' width='500' height='500' style='border:1px solid #777'/>
</body></html>
关于html - 通过鼠标和触摸在 Canvas 上绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16057256/