mobomo / sketch.js

A jQuery plugin for dead simple Canvas-based drawing.
http://intridea.github.com/sketch.js
290 stars 110 forks source link

Preloaded canvas gets cleared - why? #13

Open solars opened 11 years ago

solars commented 11 years ago

Hi there,

Thanks for this great tool! Quite handy... I just have one problem, I'm trying to load/save the drawings. With a quick test I did this over a textarea:

https://gist.github.com/solars/c1cf0efbb1b4870a4974

However, when I load the drawing, and move the mouse over and out of the canvas, or draw again on the canvas, it gets deleted... can I prevent this somehow?

Thanks, Christoph

2called-chaos commented 10 years ago

I use the exact same method to load a saved drawing and I think on redraw it removes the loaded painting (mousin & mouseout is sufficient). A solution would be awesome. I guess the loaded drawing needs to get registered in the sketch instance.

2called-chaos commented 10 years ago

Okay I've found a solution which works pretty good. The old approach saved the result as PNG but if you redraw this on the canvas you can't erase parts of it (I just assume this though). My new approach looks like this (my save and load coffee methods):

# this is what I save via AJAX
dataURL: -> JSON.stringify(@getSketch().actions)

load: (id) ->
  $.ajax "#{@getContainer().data("target-url")}/#{id}.json",
    success: (data, status, xhr) =>
      sketch = @getSketch()
      $.each data.json_data, -> sketch.actions.push(this)
      sketch.redraw()
    error: (xhr, status, msg) => alert("Failed to load sketch! #{xhr.status}: #{msg}")

My full implementation (including undo/redo function) with both old and new save/load methods: https://gist.github.com/2called-chaos/6993804