2012/05/02 17:28:53 | (127.0.0.1) {h1 pencil} {canvas {@ id:canvas; width:800; height:300; border:1px solid black;} } {p {submit {@ code:code; color:red; value:init pencil;} } grid : {input {@ id:grid; code:code; value:10;}} } {pre {@ id:code;} |//°° initpencil(); // gestion des décalages du curseur function relMouseCoords(event){ var totalOffsetX = 0, totalOffsetY = 0, canvasX = 0, canvasY = 0; var currentElement = this; do { totalOffsetX += currentElement.offsetLeft; totalOffsetY += currentElement.offsetTop; } while(currentElement = currentElement.offsetParent) canvasX = event.pageX - totalOffsetX; canvasY = event.pageY - totalOffsetY; return { x:canvasX, y:canvasY } } HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords; function initpencil() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var grid = document.getElementById("grid").value; var x, y; ctx.fillStyle = "black"; ctx.beginPath(); var MousePos = function (event) { coords = canvas.relMouseCoords(event); return {x:coords.x, y:coords.y }; }; canvas.onmousedown = function(e) { var coords = MousePos(e); x = Math.round( coords.x/grid)*grid; y = Math.round( coords.y/grid)*grid; canvas.style.cursor = "crosshair"; ctx.moveTo(x, y); }; canvas.onmouseup = function(e) { x = y = null; canvas.style.cursor = "default"; } canvas.onmousemove = function(e) { if (x == null || y == null) return; var coords = MousePos(e); x = Math.round( coords.x/grid)*grid; y = Math.round( coords.y/grid)*grid; ctx.lineTo(x, y); ctx.stroke(); ctx.moveTo(x, y); }; } //°° } °°° à mettre au point // sur iPhone/iPad : canvas.ontouchstart = function(e) { var first = e.changedTouches[0]; // tablet x = first.clientX - canvas.offsetLeft; y = first.clientY - canvas.offsetTop; ctx.moveTo(x, y); } canvas.ontouchend = function(e) { x = y = null; } canvas.ontouchmove = function(e) { if (x == null || y == null) return; var first = e.changedTouches[0]; // tablet x = first.pageX - canvas.offsetLeft; y = first.pageY - canvas.offsetTop; ctx.lineTo(x, y); ctx.stroke(); ctx.moveTo(x, y); } °°°