我目前正在學習帆布觸摸事件功能,我想在框中畫線,但繪圖沒有與鼠標指針同步。請幫助檢查我的代碼並指出我的錯誤製作 。謝謝!帆布鼠標指針未同步
這裏是編碼
<!DOCTYPE html>
<html><head>
<style>
#contain {
width: 500px;
height: 120px;
top : 15px;
margin: 0 auto;
position: relative;
}
</style>
<script>
var canvas;
var ctx;
var lastPt=null;
var letsdraw = false;
function init() {
var touchzone = document.getElementById("layer1");
touchzone.addEventListener("touchmove", draw, false);
touchzone.addEventListener("touchend", end, false);
ctx = touchzone.getContext("2d");
}
function draw(e) {
e.preventDefault();
if(lastPt!=null) {
ctx.beginPath();
ctx.moveTo(lastPt.x, lastPt.y);
ctx.lineTo(e.touches[0].pageX, e.touches[0].pageY);
ctx.stroke();
}
lastPt = {x:e.touches[0].pageX, y:e.touches[0].pageY};
}
function end(e) {
var touchzone = document.getElementById("layer1");
e.preventDefault();
// Terminate touch path
lastPt=null;
}
function clear_canvas_width()
{
var s = document.getElementById ("layer1");
var w = s.width;
s.width = 10;
s.width = w;
}
</script>
</head>
<body onload="init()">
<div id="contain">
<canvas id="layer1" width="450" height="440"
style="position: absolute; left: 0; top: 0;z-index:0; border: 1px solid #ccc;"></canvas>
</div>
</body>
</html>
您需要檢查元件偏移 – orhanhenrik
您遇到的錯誤是什麼?請考慮使用http://codereview.stackexchange.com – loxxy