Skip to content

Instantly share code, notes, and snippets.

@tec27
Created April 18, 2012 04:48
Show Gist options
  • Save tec27/2411163 to your computer and use it in GitHub Desktop.
Save tec27/2411163 to your computer and use it in GitHub Desktop.
Drawception Fixes
// ==UserScript==
// @name Drawception Fixes
// @description Fixes for some common Drawception issues
// @author tec27
// @version 0.1
// @match http://drawception.com/play/*
// ==/UserScript==
/*jshint laxcomma:true browser:true asi:true*/
var fixes = function($) {
"use strict";
var origState
, undoStack = []
, redoStack = []
, curState
, canvas
function addUndoRedoButtons() {
if(!canvas) return
var undoBtn = $('<input id="tec-undo-btn" type="button" value="Undo" class="button-nice" />')
, redoBtn = $('<input id="tec-redo-btn" type="button" value="Redo" class="button-nice" />')
, container = $('<div style="clear: both; margin: 4px 12px; border: 1px solid black; padding-top: 5px; padding-left: 5px;"/>')
container.append(undoBtn).append(redoBtn).append('<br style="clear: both; height: 1px;" />')
canvas.before(container)
undoBtn.on('click', doUndo)
redoBtn.on('click', doRedo)
addUndoStackHandlers()
}
function addUndoStackHandlers() {
curState = origState = canvas[0].toDataURL()
var wasPainting = false
canvas.on('mousedown', function(e) {
wasPainting = true
}).on('mouseup mouseleave', function(e) {
if(wasPainting) {
wasPainting = false
undoStack.push(curState)
curState = this.toDataURL()
if(redoStack.length) {
redoStack = []
}
}
})
}
function doUndo() {
var isOrigState = !undoStack.length
, data = undoStack.length ? undoStack.pop() : origState
, img = new Image()
, context = canvas[0].getContext('2d')
curState = data
if(!isOrigState) redoStack.push(canvas[0].toDataURL())
img.src = data
$(img).on('load', function() {
context.clearRect(0,0, canvas[0].width, canvas[0].height)
context.drawImage(img, 0, 0)
})
}
function doRedo() {
if(!redoStack.length) return
var data = redoStack.pop()
, img = new Image()
, context = canvas[0].getContext('2d')
undoStack.push(curState)
curState = data
img.src = data
$(img).on('load', function() {
context.clearRect(0,0, canvas[0].width, canvas[0].height)
context.drawImage(img, 0, 0)
})
}
$(document).ready(function() {
canvas = $('#drawingCanvas')
// fix for the cursor changing to a text selection one on mousedown
$(document).on('selectstart', 'canvas', function(e) { e.preventDefault() })
addUndoRedoButtons()
})
}
;(function() {
"use strict";
var el = document.createElement('script')
el.type = 'text/javascript'
el.textContent = '(' + fixes.toString() + ')(window.jQuery);'
document.body.appendChild(el)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment