いままであんまりCanvasをつかったことが無かったのですが、いよいよ本格的に取り組んでいきたいと思います。
まずは手始めに一筆書きを描画するCanvasをつくってみました。
※ PCでしかうごきません。
(function(win, doc) { "use strict"; var canvas = doc.getElementById("canvas"), 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 = [], STATUS = { START : "start", MOVE : "move", END : "end" }; elm.addEventListener(START_EVENT, handleStartEvent, false); doc.addEventListener(END_EVENT, handleEndEvent, false); setInterval(sketch, 100); function handleStartEvent(evt) { positionList = []; positionList.push({x: evt.offsetX, y: evt.offsetY, status: STATUS.START}); elm.addEventListener(MOVE_EVENT, handleMoveEvent, false); } function handleMoveEvent(evt) { positionList.push({x: evt.offsetX, y: evt.offsetY, status: STATUS.MOVE}); } function handleEndEvent(evt) { positionList.push({x: evt.offsetX, y: evt.offsetY, status: STATUS.END}); elm.removeEventListener(MOVE_EVENT, handleMoveEvent, false); } function sketch() { var length = positionList.length, i; 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 < length; i++) { if (positionList[i].status === STATUS.START) { ctx.moveTo(positionList[i].x, positionList[i].y); } ctx.lineTo(positionList[i].x, positionList[i].y); } ctx.stroke(); ctx.restore(); } } })(this, document);
初心者なんでこんな感じでしょうか。
これからすこしずつ仲良くなっていきたいと思います。Canvasと。