Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

70
LINES

< > BotCompany Repo | #1029696 // scribble.js

Document

// Original fiddle: http://jsfiddle.net/R4V97/97/
// Stefan's edit: jsfiddle.net/stefanreich/wskby4q5/

var canvas = document.getElementById("scribble"),
    ctx = canvas.getContext("2d"),
    painting = true,
    lastX = 0,
    lastY = 0,
    mouseDown = false,
    fadeInterval = 100,
    fadeSpeed = 0.025,
    strokeStyleDown = "rgba(255,255,255,1)",
    strokeStyleUp = "rgba(255,255,255,0.025)",
    sendStroke = null;

function drawStroke(x1, y1, x2, y2, mouseDown) {
  ctx.strokeStyle = mouseDown ? strokeStyleDown : strokeStyleUp;
  ctx.lineWidth = 3;
  ctx.beginPath();
  ctx.moveTo(x1, y1);
  ctx.lineTo(x2, y2);
  ctx.stroke();
}
  
document.addEventListener('DOMContentLoaded', addMouseListeners, false);

function addMouseListeners() {
  canvas.ontouchdown = function (e) {
    console.log("touchdown " + e.pageX + "/" + e.pageY);
    e.preventDefault();
  };
  
  canvas.onmousedown = function (e) {
    console.log("mousedown");
      lastX = e.pageX /*- this.offsetLeft*/;
      lastY = e.pageY /*- this.offsetTop*/;
      mouseDown = true;
  };
  
  canvas.onmouseup = function (e) {
      mouseDown = false;
  };
  
  canvas.onmouseout = function (e) {
      mouseDown = false;
  };
  
  canvas.onmousemove = function (e) {
    //console.log("mousemove");
    if (!painting) return;
    mouseX = e.pageX/* - this.offsetLeft*/;
    mouseY = e.pageY/* - this.offsetTop*/;
    drawStroke(lastX, lastY, mouseX, mouseY, mouseDown);
    if (sendStroke)
      sendStroke({x1: lastX, y1: lastY, x2: mouseX, y2: mouseY, mouseDown: mouseDown});
    lastX = mouseX;
    lastY = mouseY;
  };
  
  console.log("Registered mouse listeners on canvas");
  
  function fadeOut() {
    var r = fadeSpeed * (1 + Math.random()*0.3);
    ctx.fillStyle = "rgba(60,30,50,"+r+")";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    setTimeout(fadeOut, fadeInterval);
  }
  
  fadeOut();
}

download  show line numbers   

Travelled to 6 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1029696
Snippet name: scribble.js
Eternal ID of this version: #1029696/23
Text MD5: 671ee98950e235be5f4ccc8dc037d72c
Author: stefan
Category:
Type: Document
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-08-24 23:13:24
Source code size: 1958 bytes / 70 lines
Pitched / IR pitched: No / No
Views / Downloads: 218 / 530
Version history: 22 change(s)
Referenced in: [show references]