昨日のコード を改修してパスをたくさん描けるようにしてみました。
また、今後の拡張性を考え、
- FPSを定数で定義する
- パスの管理に多元配列を用いる
という実装に変更してみました。
(function(win, doc) { "use strict"; var canvas = doc.getElementById("canvas"), FPS = 30, // 追加 START_EVENT = "mousedown", MOVE_EVENT = "mousemove", END_EVENT = "mouseup"; init(); function init() { canvas.width = win.innerWidth; canvas.height = win.innerHeight; addSketchEventForCanvas(canvas); } function addSketchEventForCanvas(elm) { var ctx = elm.getContext("2d"), positionList = [], index = 0; // 追加 elm.addEventListener(START_EVENT, handleStartEvent, false); doc.addEventListener(END_EVENT, handleEndEvent, false); setInterval(sketch, 1000 / FPS); function handleStartEvent(evt) { positionList.push([{x: evt.offsetX, y: evt.offsetY}]); elm.addEventListener(MOVE_EVENT, handleMoveEvent, false); } function handleMoveEvent(evt) { // 多元配列で管理するように方針を変更 positionList[index].push({x: evt.offsetX, y: evt.offsetY}); } function handleEndEvent(evt) { positionList[index++].push({x: evt.offsetX, y: evt.offsetY}); elm.removeEventListener(MOVE_EVENT, handleMoveEvent, false); } function sketch() { var objLength = positionList.length, pathLength, i, j; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.save(); ctx.strokeStyle = "rgba(255, 25, 25, .5)"; ctx.lineCap = "round"; ctx.lineJoin = "miter"; ctx.miterLimit = 2; ctx.lineWidth = 2; ctx.beginPath(); for (i = 0; i < objLength; i++) { pathLength = positionList[i].length; // 多元配列で管理するように方針を変更 for (j = 0; j < pathLength; j++) { if (!j) { ctx.moveTo(positionList[i][j].x, positionList[i][j].y); } ctx.lineTo(positionList[i][j].x, positionList[i][j].y); } } ctx.stroke(); ctx.restore(); } } })(this, document);
今回は以上です。
次回は線をもっと滑らかにしたいと思います。