I'm trying to use Fabric.js with Fabric Brush This issue that I'm running into is that Fabric Brush only puts the brush strokes onto the Top Canvas and not the lower canvas. (The stock brushes in fabric.js save to the bottom canvas) I think I need to convert "this.canvas.contextTop.canvas" to an object and add that object to the the lower canvas. Any ideas?
I've tried running:
this.canvas.add(this.canvas.contextTop)
in
onMouseUp: function (pointer) {this.canvas.add(this.canvas.contextTop)}
But I'm getting the error
Uncaught TypeError: obj._set is not a function
So the contextTop is CanvasHTMLElement context. You cannot add it.
You can add to the fabricJS canvas just fabric.Object derived classes.
Look like is not possible for now.
They draw as pixel effect and then they allow you to export as an image.
Would be nice to extend fabricJS brush interface to create redrawable objects.
As of now with fabricJS and that particular version of fabric brush, the only thing you can do is:
var canvas = new fabric.Canvas(document.getElementById('c'))
canvas.freeDrawingBrush = new fabric.CrayonBrush(canvas, {
width: 70,
opacity: 0.6,
color: "#ff0000"
});
canvas.isDrawingMode = true
canvas.on('mouse:up', function(opt) {
if (canvas.isDrawingMode) {
var c = fabric.util.copyCanvasElement(canvas.upperCanvasEl);
var img = new fabric.Image(c);
canvas.contextTopDirty = true;
canvas.add(img);
canvas.isDrawingMode = false;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.1/fabric.min.js"></script>
<script src="https://tennisonchan.github.io/fabric-brush/bower_components/fabric-brush/dist/fabric-brush.min.js"></script>
<button>Enter free drawing</button>
<canvas id="c" width="500" height="500" ></canvas>
That is just creating an image from the contextTop and add as an object.
I have taken the approach suggested by AndreaBogazzi and modified the Fabric Brush so that it does the transfer from upper to lower canvas (as an image) internal to Fabric Brush. I also used some code I found which crops the image to a smaller bounding box so that is smaller than the full size of the canvas. Each of the brushes in Fabric Brush has an onMouseUp function where the code should be placed. Using the case of the SprayBrush, the original code here was:
onMouseUp: function(pointer) {
},
And it is replaced with this code:
onMouseUp: function(pointer){
function trimbrushandcopytocanvas() {
let ctx = this.canvas.contextTop;
let pixels = ctx.getImageData(0, 0, canvas.upperCanvasEl.width, canvas.upperCanvasEl.height),
l = pixels.data.length,
bound = {
top: null,
left: null,
right: null,
bottom: null
},
x, y;
// Iterate over every pixel to find the highest
// and where it ends on every axis ()
for (let i = 0; i < l; i += 4) {
if (pixels.data[i + 3] !== 0) {
x = (i / 4) % canvas.upperCanvasEl.width;
y = ~~((i / 4) / canvas.upperCanvasEl.width);
if (bound.top === null) {
bound.top = y;
}
if (bound.left === null) {
bound.left = x;
} else if (x < bound.left) {
bound.left = x;
}
if (bound.right === null) {
bound.right = x;
} else if (bound.right < x) {
bound.right = x;
}
if (bound.bottom === null) {
bound.bottom = y;
} else if (bound.bottom < y) {
bound.bottom = y;
}
}
}
// Calculate the height and width of the content
var trimHeight = bound.bottom - bound.top,
trimWidth = bound.right - bound.left,
trimmed = ctx.getImageData(bound.left, bound.top, trimWidth, trimHeight);
// generate a second canvas
var renderer = document.createElement('canvas');
renderer.width = trimWidth;
renderer.height = trimHeight;
// render our ImageData on this canvas
renderer.getContext('2d').putImageData(trimmed, 0, 0);
var img = new fabric.Image(renderer,{
scaleY: 1./fabric.devicePixelRatio,
scaleX: 1./fabric.devicePixelRatio,
left: bound.left/fabric.devicePixelRatio,
top:bound.top/fabric.devicePixelRatio
});
this.canvas.clearContext(ctx);
canvas.add(img);
}
setTimeout(trimbrushandcopytocanvas, this._interval); // added delay because last spray was on delay and may not have finished
},
The setTimeout function was used because Fabric Brush could still be drawing to the upper canvas after the mouseup event occurred, and there were occasions where the brush would continue painting the upper canvas after its context was cleared.
Related
I'm trying to make a simple graphics program for doodling and such, but I'm having some trouble with the line tools provided by PIXI.Graphics().
I draw lines by using events such as pointerdown, pointermove, etc. Saving the last coordinate and then using moveTo and lineTo to draw a continuous line until you trigger pointerup. When drawing a line however gaps appear in semi-regular intervals.
Those gaps are always in the color used in the beginFill() fill statement. Even if I use multiple colors, they will appear in the line, making it not really "gaps" but wrongly colored lines.
When a long line is drawn via code, the same error does not seem to occur.
I'm quite stumped by the behaviour and it would be nice if you could help me out!
Here is the code I used:
let app;
let graphics;
var isDrawing = false;
var x = 0;
var y = 0;
var count = 0;
window.onload = function(){
var canvasContainer = document.getElementById("areaCanvasContainer");
//Create a Pixi Application
app = new PIXI.Application({
width: 600,
height: 500,
antialias: false,
transparent: false,
resolution: 1,
forceCanvas: false,
backgroundColor: 0xFFFFFF
});
canvasContainer.appendChild(app.view);
graphics = new PIXI.Graphics();
graphics.interactive = true;
graphics.buttonMode = true;
graphics.beginFill(0xFFFFFF);
graphics.drawRect(0, 0, 600, 500);
graphics.endFill();
graphics.lineStyle(3, 0x000000,1.0,0.5,false);
graphics.on("pointerdown", mousedown);
graphics.on("pointermove", mousemove);
graphics.on("pointerup", mouseup);
graphics.on("pointerupoutside", mouseup);
app.stage.addChild(graphics);
}
function mousedown(e) {
x = e.data.global.x;
y = e.data.global.y;
isDrawing = true;
}
function mousemove(e) {
if (isDrawing === true) {
if(Math.abs(x - e.data.global.x) > 2 || Math.abs(y - e.data.global.y ) > 2 ){
drawLine(graphics, x, y, e.data.global.x, e.data.global.y);
x = e.data.global.x;
y = e.data.global.y;
}
}
}
function mouseup(e) {
if (isDrawing === true) {
drawLine(graphics, x, y, e.data.global.x, e.data.global.y);
x = 0;
y = 0;
isDrawing = false;
}
}
function drawLine(graphics, x1, y1, x2, y2) {
if(!(x1 === x2 && y1 === y2)){
graphics.endFill();
graphics.moveTo(x1, y1);
graphics.lineTo(x2, y2);
}
}
I just started using Canvas for my web game project and faced a problem.
I'm using this code to render the game:
function render(f){
if(charoffset.x == null) charoffset.x = charpos.x*tilescale;
if(charoffset.y == null) charoffset.y = charpos.y*tilescale;
if(!tiles) tiles = [];
if(f){
log("Welcome.","gold");
}
var canPassthrough = function (){
if ((def.passable(this.type))&&(typeof this.type !== 'undefined')){
return true;
}
else {
return false;
}
};
if(!f) lighting.update();
canvas.getContext("2d").clearRect(0,0,sq,sq);
for (var i = 0; i < map[charlvl].length; i++){
if(!tiles[i]) tiles[i] = [];
for (var j = 0; j < map[charlvl][i].length; j++){
if(!tiles[i][j]) tiles[i][j] = placetile(i,j);
drawtile(tiles[i][j]);
placeitem(i,j);
}
}
ui.overlay.text("casting shadows...");
//shadowcaster(20);
var tex = document.createElement("img");
tex.src = "../img/charplaceholder.png";
var hero = canvas.getContext("2d");
hero.globalAlpha = 1.0;
if(charoffset.x>=map_scroll.x&&charoffset.y*tilescale>=map_scroll.y){
var pos = {
x: charoffset.x - map_scroll.x - tilescale,
y: charoffset.y - map_scroll.y - tilescale
};
hero.drawImage(tex,pos.x,pos.y,tilescale,tilescale);
}
function placetile(x,y){
var obj = {};
obj.type = map[charlvl][x][y].id;
obj.canPassthrough = canPassthrough;
obj.state = {explored: false, lit: false};
obj.coords = {x:x,y:y};
obj.offset = {x:x*tilescale,y:y*tilescale};
return obj;
}
function drawtile(t){
if(t.offset.x>=map_scroll.x&&t.offset.y>=map_scroll.y){
var pos = {
x: t.offset.x - map_scroll.x - tilescale,
y: t.offset.y - map_scroll.y - tilescale
};
if(!t.state.explored&&!t.state.lit){
return false;
}
else if(t.state.lit&&t.state.explored){
var tex = document.createElement("img");
var tile = canvas.getContext("2d");
tex.src = def.css.tile(t.type);
tile.globalAlpha = 1.0;
tile.drawImage(tex,pos.x,pos.y,tilescale,tilescale);
return true;
}
else if(t.state.explored&&!t.state.lit){
var tex = document.createElement("img");
var tile = canvas.getContext("2d");
tex.src = def.css.tile(t.type);
tile.globalAlpha = 0.25;
tile.drawImage(tex,pos.x,pos.y,tilescale,tilescale);
return true;
}
}
}
function placeitem(x,y){
return;
if (loot[charlvl][x][y]){
for(var i=0;i<loot[charlvl][x][y].length;i++){
var tile = document.createElement("div");
var tileid = loot[charlvl][x][y][i].type;
tile.className = def.css.item(tileid);
tile.coords = {x:x,y:y};
document.getElementById("x" + x + "y" + y).appendChild(tile);
}
}
}
if(f){
camera.center(charpos.x,charpos.y);
ui.overlay.text("loading the dungeon...");
ui.overlay.hide();
}
}
Function render() is fired by various events, such as character moving, map dragging, lighting update, etc.
This is the result:
I would like to add inset shadows to walls so it's more clearly visible those are walls. I tried experimenting with canvas context shadows, and used this:
It's supposed to draw a transparent rectangle and a shadow for it at 100, 100 with size 20, 20, however this applies shadow to every drawn tile instead.
I feel like I'm using drawing wrong. Can anyone explain how to effectively
use canvas to achieve desired effect?
Do not use the 2D API shadow options , they are very very slow ( and that is an understatement of how bad they are). You are much better off creating the shadows as part of the tile set and rendering them with either ctx.globalAlpha set to less than 1 and/or use one of the many composite modes. Eg ctx.globalCompositeOperation = "multiply"; Or overlay, color-burn, hard-light, and soft-light. You can even use a combination to get a very good shadow effect.
Creating the shadows as part of the tile set will give a much more realistic effect as the shadow API is just for shadows cast from flat object floating above a flat surface, not for 3D objects protruding from the screen that may have sloped sides in the z direction.
If you do not wish to create the shadows as part of the tile set consider creating the shadow tile set at onload using an off screen canvas via the shadow API options. Then render from that to the canvas using alpha and composite options
I want to create a Canvas in which there will be two areas (Left and right), Left panel will contain some shapes which will be draggable(static as well) and on the right side I would be able to drop them, but I am facing following problem,
I am not able to make the shapes which i draw on the left side, draggable, because there is no id associated with them.
I do not know how to make some particular area droppable.
Here is code to visualize what I am trying to achieve-
<body>
<canvas id="myCanvas" width="800" height="600" style="border:1px solid #000000;">
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(250,0);
ctx.lineTo(250,600);
ctx.stroke();
ctx.fillStyle = "#FF0000";
ctx.fillRect(50,50,160,25);
ctx.fillStyle = "#0000FF";
ctx.font = "15px";
ctx.strokeText("Draggable Elements here",57,67);
ctx.fillStyle = "#FF0000";
ctx.fillRect(500,50,130,25);
ctx.font = "15px";
ctx.strokeText("Droppable area Here",510,67);
</script>
</body>
Here is the JS fiddle for the same -
http://jsfiddle.net/akki166786/4tfyy4o5/
so if anybody can shed some light on how can I achieve this, it will be a great help.
Thanks in Advance
Drag and drop in specifik area
UPDATE: Copy of box remains at original position while it's being moved.
First you need to be able to detect your rectangles. You do this by making then into objects in your code:
function box(x,y,w,h,rgb) {
this.x = x,
this.y = y;
this.xS = x; //saving x
this.yS = y; //saving y
this.w = w;
this.h = h;
this.rgb = rgb;
//to determine if the box is being draged
this.draging = false;
}
No you need to add an event listener to determine if someone is clicking, you also need to determine if the person clicked in one of your boxes.
c.addEventListener("mousedown",down);
c.addEventListener("mousemove",move);
c.addEventListener("mouseup",up);
So events have been made to detect when the mouse button is pressed down, released back up and if the mouse moves within the canvas. To these events we have functions, down(), move() and up(), ready to be executed.
All functions will be visible in the example below.
When we're happily draging our boxes and releasing our mouse button, we need to check if the box was dropped in the dropable area. We do this in the up()-function. If the drop was OK, the box can stay, otherwise we send it back to where it came from.
Working example
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
c.width = 600;
c.height = 300;
//My mouse coordinates
var x,y;
c.addEventListener("mousedown",down);
c.addEventListener("mousemove",move);
c.addEventListener("mouseup",up);
//I'll save my boxes in this array
var myBoxes = new Array();
//This function describes what a box is.
//Each created box gets its own values
function box(x,y,w,h,rgb) {
this.x = x,
this.y = y;
this.xS = x; //saving x
this.yS = y; //saving y
this.w = w;
this.h = h;
this.rgb = rgb;
//to determine if the box is being draged
this.draging = false;
}
//Let's make some boxes!!
myBoxes[0] = new box(10,10,50,100,"green");
myBoxes[1] = new box(80,50,100,75,"blue");
myBoxes[2] = new box(40,150,20,70,"yellow");
//here we draw everything
function draw() {
ctx.clearRect(0,0,c.width,c.height);
//Dropable area
ctx.fillStyle="red";
ctx.fillRect(c.width/2,0,c.width,c.height);
//Boxes!
for (var i = 0; i<myBoxes.length; i++) {
var b = myBoxes[i];
//NEW CODE FOR UPDATE
if (b.draging) { //box on the move
//Also draw it on the original spot
ctx.fillStyle="grey"; //I chose a different color to make it appear more as a shadow of the box that's being moved.
ctx.fillRect(b.xS,b.yS,b.w,b.h);
ctx.strokeRect(b.xS,b.yS,b.w,b.h);
}
//End of new code for update
ctx.fillStyle=b.rgb;
ctx.fillRect(b.x,b.y,b.w,b.h);
ctx.strokeRect(b.x,b.y,b.w,b.h);
}
//Let's keep re-drawing this
requestAnimationFrame(draw);
}
function down(event) {
event = event || window.event;
x = event.pageX - c.offsetLeft,
y = event.pageY - c.offsetTop;
for (var i = 0; i<myBoxes.length; i++) {
var b = myBoxes[i];
if (x>b.x && x<b.x+b.w && y>b.y && y<b.y+b.h) {
b.draging = true;
}
}
}
function move(event) {
event = event || window.event;
x = event.pageX - c.offsetLeft,
y = event.pageY - c.offsetTop;
for (var i = 0; i<myBoxes.length; i++) {
var b = myBoxes[i];
if (b.draging) {
b.x = x;
b.y = y;
}
}
}
function up(event) {
event = event || window.event;
x = event.pageX - c.offsetLeft,
y = event.pageY - c.offsetTop;
for (var i = 0; i<myBoxes.length; i++) {
var b = myBoxes[i];
if (b.draging) {
//Let's see if the rectangle is inside the dropable area
if (b.x>c.width/2) {
//Yes is it!
b.x = x;
b.y = y;
b.draging = false;
}
else {
//No it's not, sending it back to its ordiginal spot
b.x = b.xS;
b.y = b.yS;
b.draging = false;
}
}
}
}
draw();
canvas {
border: 1px solid black;
}
<canvas id="canvas"></canvas>
You're using just one canvas, maybe it would be better if you use two separate canvas, one for each element you want to handle on page. so you'll have one element ID for each one.
plus. if your drawing is simple, consider using a div for it instead a canvas
Once drawn to the canvas, shapes(or lines, images, everything) are no longer accessible.
What you will need to do is store each shape in an object in your code. For example:
var rectangle = {
width: 100,
height: 100,
x: 50,
y: 50
}
Then when you drag rectangle, you will need to update it's x and y properties on mouseup (or while it's being dragged if you want a drag preview).
I have a fabricjs canvas that I need to be able to zoom in and out and also change the image/object inside several times.
For this I setup the canvas in the first time the page loads like this:
fabric.Object.prototype.hasBorders = false;
fabric.Object.prototype.hasControls = false;
canvas = new fabric.Canvas('my_canvas', {renderOnAddRemove: false, stateful: false});
canvas.defaultCursor = "pointer";
canvas.backgroundImageStretch = false;
canvas.selection = false;
canvas.clear();
var image = document.getElementById('my_image');
if (image != null) {
imageSrc = image.src;
if(imageSrc.length > 0){
fabric.Image.fromURL(imageSrc, function(img) {
img = scaleImage(canvas, img); //shrinks the image to fit the canvas
img.selectable = false;
canvas.centerObject(img);
canvas.setActiveObject(img);
canvas.add(img);
});
}
}
canvas.deactivateAll().renderAll();
Then when I need to change the image/object in the canvas or when the page reloads, I try to reset the canvas like this:
canvas.clear();
canvas.remove(canvas.getActiveObject());
var image = document.getElementById('my_image');
if (image != null) {
imageSrc = image.src;
if(imageSrc.length > 0){
fabric.Image.fromURL(imageSrc, function(img) {
img = scaleImage(canvas, img); //shrinks the image to fit the canvas
img.selectable = false;
canvas.centerObject(img);
canvas.setActiveObject(img);
canvas.add(img);
});
}
}
Not sure if it matters but the way I change the image is by changing the source in 'my_image' and reseting the canvas with the above method.
This works well until I use canvas.zoomToPoint, as per this thread, after this, the image/object starts changing position when I reset the zoom or click the canvas with the mouse while it is zoomed, seeming to jump at each change in the top left corner direction, eventually disappearing from view.
Reset Zoom:
canvas.setZoom(1);
resetCanvas(); //(above method)
How can I restore the image/object position?
I tried doing the initial setup instead of the reset and seamed to work visually but was in fact adding a new layer of upper canvas at each new setup so it is no good.
Is there a way to reset the canvas to original state without causing this behavior and still be able to zoom in/out correctly?
Although this question is very old, here is what I did using the current version of fabric.js 2.2.4:
canvas.setViewportTransform([1,0,0,1,0,0]);
For your information: zooming to a point is a recalculation of the viewport transformation. The upper matrix is this is the initial viewport transform matrix.
I eventually fixed the problems I was having.
To reset the zoom, instead of just setting the zoom to 1 with canvas.setZoom(1), I reapplied the canvas.zoomToPoint method to the same point but with zoom 1, to force the initial zoom but regarding the same point that was used to zoom in.
As for the problem of restoring the image position in canvas (after panning for instance) it is as simple as removing the image, centering it in the canvas and re-adding it to the canvas as was done when adding first time:
var img = canvas.getActiveObject();
canvas.remove(img);
canvas.centerObject(img);
canvas.setActiveObject(img);
canvas.add(img);
canvas.renderAll();
See below snippet - here I do the same - zooming together, but degrouping the objects in case somebody clicks on it.
The problem to get to original object properties can be solved, ungrouping the group and creating copies of them and reattaching - a bit annoying, but the only solution I found.
<script id="main">
// canvas and office background
var mainGroup;
var canvas = this.__canvas = new fabric.Canvas('c');
fabric.Object.prototype.transparentCorners = false;
fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center';
createOnjects(canvas);
// events - zoom
$(canvas.wrapperEl).on('mousewheel', function(e) {
var target = canvas.findTarget(e);
var delta = e.originalEvent.wheelDelta / 5000;
if (target) {
target.scaleX += delta;
target.scaleY += delta;
// constrain
if (target.scaleX < 0.1) {
target.scaleX = 0.1;
target.scaleY = 0.1;
}
// constrain
if (target.scaleX > 10) {
target.scaleX = 10;
target.scaleY = 10;
}
target.setCoords();
canvas.renderAll();
return false;
}
});
// mouse down
canvas.on('mouse:up', function(options) {
if (options.target) {
var thisTarget = options.target;
var mousePos = canvas.getPointer(options.e);
if (thisTarget.isType('group')) {
// unGroup
console.log(mousePos);
var clone = thisTarget._objects.slice(0);
thisTarget._restoreObjectsState();
for (var i = 0; i < thisTarget._objects.length; i++) {
var o = thisTarget._objects[i];
if (o._element.alt == "officeFloor")
continue;
else {
if (mousePos.x >= o.originalLeft - o.currentWidth / 2 && mousePos.x <= o.originalLeft + o.currentWidth / 2
&& mousePos.y >= o.originalTop - o.currentHeight / 2 && mousePos.y <= o.originalTop + o.currentHeight / 2)
console.log(o._element.alt);
}
}
// remove all objects and re-render
canvas.remove(thisTarget);
canvas.clear().renderAll();
var group = new fabric.Group();
for (var i = 0; i < clone.length; i++) {
group.addWithUpdate(clone[i]);
}
canvas.add(group);
canvas.renderAll();
}
}
});
// functions
function createOnjects(canvas) {
// ToDo: jQuery.parseJSON() for config file (or web service)
fabric.Image.fromURL('pics/OfficeFloor.jpg', function(img) {
var back = img.set({ left: 100, top: 100 });
back._element.alt = "officeFloor";
back.hasControls = false;
fabric.Image.fromURL('pics/me.png', function(img) {
var me = img.set({ left: -420, top: 275 });
me._element.alt = "me";
console.log(me);
var group = new fabric.Group([ back, me], { left: 700, top: 400, hasControls: false });
canvas.clear().renderAll();
canvas.add(group);
// remove all objects and re-render
});
});
}
</script>
Hello i create program like a paint on HTML5 canvas. I have problem i need create few tools drawing and zoom. I don't have idea how to create zoom without delay. Drawing example: http://jsfiddle.net/x5rrvcr0/
How i can zooming my drawings?
drawing code:
<style>
canvas {
background-color: #CECECE;
}
html, body {
background-color: #FFFFFF;
}
</style>
<script>
$(document).ready(function () {
var paintCanvas = document.getElementById("paintCanvas");
var paintCtx = paintCanvas.getContext("2d");
var size = 500;
paintCanvas.width = size;
paintCanvas.height = size;
var draw = false;
var prevMouseX = 0;
var prevMouseY = 0;
function getMousePos(canvas, evt) {
evt = evt.originalEvent || window.event || evt;
var rect = canvas.getBoundingClientRect();
if (evt.clientX !== undefined && evt.clientY !== undefined) {
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
}
$("#paintCanvas").on("mousedown", function(e) {
draw = true;
var coords = getMousePos(paintCanvas);
prevMouseX = coords.x;
prevMouseY = coords.y;
});
$("#paintCanvas").on("mousemove", function(e) {
if(draw) {
var coords = getMousePos(paintCanvas, e);
paintCtx.beginPath();
paintCtx.lineWidth = 10;
paintCtx.strokeStyle = "#000000";
paintCtx.moveTo(prevMouseX, prevMouseY);
paintCtx.lineTo(coords.x, coords.y);
paintCtx.stroke();
prevMouseX = coords.x;
prevMouseY = coords.y;
}
});
$("#paintCanvas").on("mouseup", function(e) {
draw = false;
});
});
</script>
<body>
<canvas id="paintCanvas"></canvas>
</body>
If you want to keep the pixelated effect in the zoom, you need to draw on a temp canvas, then only after copy that temp canvas to the main screen.
You no longer need to zoom in the temp canvas, just draw on 1:1 scale always. When copying to the view canvas, then you apply the zoom (and maybe translate) that you want.
Keep in mind that drawings are anti-aliased, so you when zooming you will see some shades of grey when drawing in black, for instance.
I kept the recording code of #FurqanZafar since it is a good idea to record things in case you want to perform undo : in that case just delete the last record entry and redraw everything.
http://jsfiddle.net/gamealchemist/x5rrvcr0/4/
function updatePaintCanvas() {
paintContext.clearRect(0, 0, paintContext.canvas.width, paintContext.canvas.height);
paintContext.save();
paintContext.translate(cvSize * 0.5, cvSize * 0.5);
paintContext.scale(scale, scale);
paintContext.drawImage(drawCanvas, -cvSize * 0.5, -cvSize * 0.5);
paintContext.restore();
}
Heres the updated fiddle: http://jsfiddle.net/x5rrvcr0/2/ with basic zooming functionality
If you draw multiple paths on mouse move then your sketch will appear broken or disconnected, instead you should only stroke a single path until "mouseup" event.
You can then store these paths in an array and later redraw them at different zoom levels:
function zoom(context, paths, styles, scale) {
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
context.save();
applyStyles(context, styles);
scaleFromCenter(context, scale);
for (var i = 0; i < paths.length; i++) {
context.beginPath();
context.moveTo(paths[i][0].x, paths[i][0].y);
for (var j = 1; j < paths[i].length; j++)
context.lineTo(paths[i][j].x, paths[i][j].y);
context.stroke();
}
context.restore();
};