The code below allows to click on a canvas with a background image and draw a point. I would like to give the change to the user to change the default image, so I have added an input file element. So go to the snippet and follow this steps:
Step 1: click on the first default image "Ziiweb". The coordinate is
shown in the textarea.
Step 2: load/preview a new image using the Browse button, and click on it. As you can see the coordinates of the first image are kept, why?
Hint: after previewing a new image, and click over it, the function mousedown() is called twice.
$.fn.canvasAreaDraw = function (options) {
this.each(function (index, element) {
init.apply(element, [index, element, options]);
});
}
var init = function (index, input, options) {
var points, activePoint, settings;
var $reset, $canvas, ctx, image;
var draw, mousedown, stopdrag, move, resize, reset, resot, rightclick, record, previewImage;
mousedown = function (e) {
console.log('mousedown');
console.log(points);
console.log(points.length);
var x, y, dis, lineDis, insertAt = points.length;
e.preventDefault();
if (!e.offsetX) {
e.offsetX = (e.pageX - $(e.target).offset().left);
e.offsetY = (e.pageY - $(e.target).offset().top);
}
x = e.offsetX;
y = e.offsetY;
points.splice(insertAt, 0, Math.round(x), Math.round(y));
activePoint = insertAt;
$(this).on('mousemove', move);
record();
return false;
};
record = function () {
$(input).val(points.join(','));
};
settings = $.extend({
imageUrl: $(this).attr('data-image-url')
}, options);
points = []; //I expected this to reset the points list!!!, but no....
if (!$(this).is('canvas')) {
$canvas = $('<canvas>');
} else {
$canvas = $(this);
}
ctx = $canvas[0].getContext('2d');
image = new Image();
$(this).prev().prev().val('');
resize = function () {
$canvas.attr('height', image.height).attr('width', image.width);
draw();
};
if (settings.imageUrl) {
image.src = settings.imageUrl;
} else {
image.src = options;
}
$canvas.css({
background: 'url(' + image.src + ')'
});
$(input).after('<br>', $canvas);
$(document).ready(function () {
$canvas.on('mousedown', mousedown);
});
};
//LOAD IMAGE
previewImage = function () {
var aux = $(this).prev();
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
aux.canvasAreaDraw(e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
}
$(document).ready(function () {
$('.canvas-area').canvasAreaDraw();
$('.imgInp').on('change', previewImage);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="canvas-area" data-image-url="http://www.ziiweb.com/images/logo.png"></textarea>
<input type='file' class="imgInp" id="jander" />
Because each time you attach a new image, the document.readyevent fires and attaches a new mousedown handler to the canvas.
$.fn.canvasAreaDraw = function (options) {
this.each(function (index, element) {
init.apply(element, [index, element, options]);
});
}
var init = function (index, input, options) {
var points, activePoint, settings;
var $reset, $canvas, ctx, image;
var draw, mousedown, stopdrag, move, resize, reset, resot, rightclick, record, previewImage;
mousedown = function (e) {
console.log('mousedown');
console.log(points);
console.log(points.length);
var x, y, dis, lineDis, insertAt = points.length;
e.preventDefault();
if (!e.offsetX) {
e.offsetX = (e.pageX - $(e.target).offset().left);
e.offsetY = (e.pageY - $(e.target).offset().top);
}
x = e.offsetX;
y = e.offsetY;
points.splice(insertAt, 0, Math.round(x), Math.round(y));
activePoint = insertAt;
$(this).on('mousemove', move);
record();
return false;
};
record = function () {
$(input).val(points.join(','));
};
settings = $.extend({
imageUrl: $(this).attr('data-image-url')
}, options);
points = []; //I expected this to reset the points list!!!, but no....
if (!$(this).is('canvas')) {
$canvas = $('<canvas>');
} else {
$canvas = $(this);
}
ctx = $canvas[0].getContext('2d');
image = new Image();
$(this).prev().prev().val('');
resize = function () {
$canvas.attr('height', image.height).attr('width', image.width);
draw();
};
if (settings.imageUrl) {
image.src = settings.imageUrl;
} else {
image.src = options;
}
$canvas.css({
background: 'url(' + image.src + ')'
});
$(input).after('<br>', $canvas);
$(document).ready(function () {
alert('attaching a new mousedown event!');
$canvas.on('mousedown', mousedown);
});
};
//LOAD IMAGE
previewImage = function () {
var aux = $(this).prev();
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
aux.canvasAreaDraw(e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
}
$(document).ready(function () {
$('.canvas-area').canvasAreaDraw();
$('.imgInp').on('change', previewImage);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="canvas-area" data-image-url="http://www.ziiweb.com/images/logo.png"></textarea>
<input type='file' class="imgInp" id="jander" />
The solution being to attach the event somewhere else, or to use a flag.
$.fn.canvasAreaDraw = function (options) {
this.each(function (index, element) {
init.apply(element, [index, element, options]);
});
}
var init = function (index, input, options) {
var points, activePoint, settings;
var $reset, $canvas, ctx, image;
var draw, mousedown, stopdrag, move, resize, reset, resot, rightclick, record, previewImage;
mousedown = function (e) {
console.log('mousedown');
console.log(points);
console.log(points.length);
var x, y, dis, lineDis, insertAt = points.length;
e.preventDefault();
if (!e.offsetX) {
e.offsetX = (e.pageX - $(e.target).offset().left);
e.offsetY = (e.pageY - $(e.target).offset().top);
}
x = e.offsetX;
y = e.offsetY;
points.splice(insertAt, 0, Math.round(x), Math.round(y));
activePoint = insertAt;
$(this).on('mousemove', move);
record();
return false;
};
record = function () {
$(input).val(points.join(','));
};
settings = $.extend({
imageUrl: $(this).attr('data-image-url')
}, options);
points = []; //I expected this to reset the points list!!!, but no....
if (!$(this).is('canvas')) {
$canvas = $('<canvas>');
} else {
$canvas = $(this);
}
ctx = $canvas[0].getContext('2d');
image = new Image();
$(this).prev().prev().val('');
resize = function () {
$canvas.attr('height', image.height).attr('width', image.width);
draw();
};
if (settings.imageUrl) {
image.src = settings.imageUrl;
} else {
image.src = options;
}
$canvas.css({
background: 'url(' + image.src + ')'
});
$(input).after('<br>', $canvas);
$(document).ready(function () {
if(first){
alert('attaching a new mousedown event!');
first= false;
$canvas.on('mousedown', mousedown);
}
});
};
var first = true;
//LOAD IMAGE
previewImage = function () {
var aux = $(this).prev();
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
aux.canvasAreaDraw(e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
}
$(document).ready(function () {
$('.canvas-area').canvasAreaDraw();
$('.imgInp').on('change', previewImage);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="canvas-area" data-image-url="http://www.ziiweb.com/images/logo.png"></textarea>
<input type='file' class="imgInp" id="jander" />
Related
I am erasing the canvas drawing 1 time then Undo works fine, but when I erase more than 1 time then the Undo work as a line stroke, it works for the last step to erase but other are working as line stroke please see below code:
function Sketchpad(config) {
// Enforces the context for all functions
for (var key in this.constructor.prototype) {
this[key] = this[key].bind(this);
}
// Warn the user if no DOM element was selected
if (!config.hasOwnProperty('element')) {
console.error('SKETCHPAD ERROR: No element selected');
return;
}
this.element = config.element;
// Width can be defined on the HTML or programatically
this._width = config.width || $(this.element).attr('data-width') || 0;
this._height = config.height || $(this.element).attr('data-height') || 0;
// Pen attributes
this.color = config.color || $(this.element).attr('data-color') || '#000000';
this.penSize = config.penSize || $(this.element).attr('data-penSize') || 5;
// ReadOnly sketchpads may not be modified
this.readOnly = config.readOnly ||
$(this.element).attr('data-readOnly') ||
false;
if (!this.readOnly) {
$(this.element).css({cursor: 'crosshair'});
}
// Stroke control variables
this.strokes = config.strokes || [];
console.log(this.strokes)
this._currentStroke = {
color: null,
size: null,
lines: [],
};
// Undo History
this.undoHistory = (!bErasing) ? (config.undoHistory || []) : [];
// Animation function calls
this.animateIds = [];
// Set sketching state
this._sketching = false;
// Setup canvas sketching listeners
this.reset();
}
//
// Private API
//
Sketchpad.prototype._cursorPosition = function(event) {
return {
x: event.pageX - $(this.canvas).offset().left,
y: event.pageY - $(this.canvas).offset().top,
};
};
Sketchpad.prototype._draw = function(start, end, color, size) {
this._stroke(start, end, color, size, 'source-over');
};
Sketchpad.prototype._erase = function(start, end, color, size) {
this._stroke(start, end, color, size, 'destination-out');
};
Sketchpad.prototype._stroke = function(start, end, color, size) {
this.context.save();
if(bErasing){
this.context.globalCompositeOperation = "destination-out";
}else{
this.context.globalCompositeOperation = "source-over";
}
// if(size === 7 || size === 13){
// console.log(size)
// this.context.lineJoin = 'square';
// this.context.lineCap = 'square';
// }
// else{
this.context.lineJoin = 'round';
this.context.lineCap = 'round';
// }
this.context.strokeStyle = color;
this.context.lineWidth = size;
// switch(size){
// case 2:
// this.context.globalAlpha = 1;
// break;
// case 7:
// this.context.globalAlpha = 0.7;
// break;
// case 13:
// this.context.globalAlpha = 0.4;
// break;
// default:
// this.context.globalAlpha = 0.2;
// }
this.context.beginPath();
this.context.moveTo(start.x, start.y);
this.context.lineTo(end.x, end.y);
this.context.closePath();
this.context.stroke();
this.context.restore();
};
//
// Callback Handlers
//
Sketchpad.prototype._mouseDown = function(event) {
this._lastPosition = this._cursorPosition(event);
this._currentStroke.color = this.color;
this._currentStroke.size = this.penSize;
this._currentStroke.lines = [];
// console.log(this._currentStroke.lines)
this._sketching = true;
this.canvas.addEventListener('mousemove', this._mouseMove);
};
Sketchpad.prototype._mouseUp = function(event) {
if (this._sketching) {
this.strokes.push($.extend(true, {}, this._currentStroke));
this._sketching = false;
}
this.canvas.removeEventListener('mousemove', this._mouseMove);
};
Sketchpad.prototype._mouseMove = function(event) {
var currentPosition = this._cursorPosition(event);
this._draw(this._lastPosition, currentPosition, this.color, this.penSize);
this._currentStroke.lines.push({
start: $.extend(true, {}, this._lastPosition),
end: $.extend(true, {}, currentPosition),
});
this._lastPosition = currentPosition;
};
Sketchpad.prototype._touchStart = function(event) {
event.preventDefault();
if (this._sketching) {
return;
}
this._lastPosition = this._cursorPosition(event.changedTouches[0]);
this._currentStroke.color = this.color;
this._currentStroke.size = this.penSize;
this._currentStroke.lines = [];
this._sketching = true;
this.canvas.addEventListener('touchmove', this._touchMove, false);
};
Sketchpad.prototype._touchEnd = function(event) {
event.preventDefault();
if (this._sketching) {
this.strokes.push($.extend(true, {}, this._currentStroke));
this._sketching = false;
}
this.canvas.removeEventListener('touchmove', this._touchMove);
};
Sketchpad.prototype._touchCancel = function(event) {
event.preventDefault();
if (this._sketching) {
this.strokes.push($.extend(true, {}, this._currentStroke));
this._sketching = false;
}
this.canvas.removeEventListener('touchmove', this._touchMove);
};
Sketchpad.prototype._touchLeave = function(event) {
event.preventDefault();
if (this._sketching) {
this.strokes.push($.extend(true, {}, this._currentStroke));
this._sketching = false;
}
this.canvas.removeEventListener('touchmove', this._touchMove);
};
Sketchpad.prototype._touchMove = function(event) {
event.preventDefault();
var currentPosition = this._cursorPosition(event.changedTouches[0]);
this._draw(this._lastPosition, currentPosition, this.color, this.penSize);
this._currentStroke.lines.push({
start: $.extend(true, {}, this._lastPosition),
end: $.extend(true, {}, currentPosition),
});
this._lastPosition = currentPosition;
};
//
// Public API
//
Sketchpad.prototype.reset = function() {
// Set attributes
this.canvas = $(this.element)[0];
this.canvas.width = this._width;
this.canvas.height = this._height;
this.context = this.canvas.getContext('2d');
// Setup event listeners
this.redraw(this.strokes);
if (this.readOnly) {
return;
}
// Mouse
this.canvas.addEventListener('mousedown', this._mouseDown);
this.canvas.addEventListener('mouseout', this._mouseUp);
this.canvas.addEventListener('mouseup', this._mouseUp);
// Touch
this.canvas.addEventListener('touchstart', this._touchStart);
this.canvas.addEventListener('touchend', this._touchEnd);
this.canvas.addEventListener('touchcancel', this._touchCancel);
this.canvas.addEventListener('touchleave', this._touchLeave);
};
Sketchpad.prototype.drawStroke = function(stroke) {
for (var j = 0; j < stroke.lines.length; j++) {
var line = stroke.lines[j];
this._draw(line.start, line.end, stroke.color, stroke.size);
}
};
Sketchpad.prototype.erase = function() {
// this._erase(line.start, line.end, stroke.color, stroke.size);
};
Sketchpad.prototype.redraw = function(strokes) {
for (var i = 0; i < strokes.length; i++) {
this.drawStroke(strokes[i]);
}
};
Sketchpad.prototype.toObject = function() {
return {
width: this.canvas.width,
height: this.canvas.height,
strokes: this.strokes,
undoHistory: this.undoHistory,
};
};
Sketchpad.prototype.toJSON = function() {
return JSON.stringify(this.toObject());
};
Sketchpad.prototype.animate = function(ms, loop, loopDelay) {
this.clear();
var delay = ms;
var callback = null;
for (var i = 0; i < this.strokes.length; i++) {
var stroke = this.strokes[i];
for (var j = 0; j < stroke.lines.length; j++) {
var line = stroke.lines[j];
callback = this._draw.bind(this, line.start, line.end,
stroke.color, stroke.size);
this.animateIds.push(setTimeout(callback, delay));
delay += ms;
}
}
if (loop) {
loopDelay = loopDelay || 0;
callback = this.animate.bind(this, ms, loop, loopDelay);
this.animateIds.push(setTimeout(callback, delay + loopDelay));
}
};
Sketchpad.prototype.cancelAnimation = function() {
for (var i = 0; i < this.animateIds.length; i++) {
clearTimeout(this.animateIds[i]);
}
};
Sketchpad.prototype.clear = function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
};
Sketchpad.prototype.undo = function() {
this.clear();
var stroke = this.strokes.pop();
if (stroke) {
this.undoHistory.push(stroke);
this.redraw(this.strokes);
}
};
Sketchpad.prototype.redo = function() {
var stroke = this.undoHistory.pop();
if (stroke) {
this.strokes.push(stroke);
this.drawStroke(stroke);
}
};
and also having issue while trying the change the texture of brushes according to the pen size.
eraser is working fine and undo is also working fine the only issue is while we erase more than once, then try to undo then last erase is return to real drawing, but other previous works like as the line stroke and display the drawing as per eraser mouse move in canvas.
This is my my function to call above methods:
var x = "#CB7342",
y = 2;
var bErasing = false;
var canvas, canvasWidth, canvasHeight;
var ctx;
var lastPt=null;
var pathsry = [];
var points = [];
var state;
var colour;
// past states
function ySize(size) {
y = size;
sketchpad.penSize = y;
}
var sketchpad;
function undo(){
bErasing = false;
sketchpad.undo();
if($('#erase').hasClass('active')){
bErasing = true;
}
}
function init() {
canvas = document.getElementById('sheet');
ctx = canvas.getContext('2d');
var canvasOffset = $('#sheet').offset();
var parent = canvas.parentNode;
canvas.width = parent.clientWidth;
canvas.height = parent.clientHeight;
// alert(bErasing)
sketchpad = new Sketchpad({
element: '#sheet',
width: canvas.width,
height: canvas.height,
color: null,
penSize: 2,
globalAlpha: 0.1
});
}
$(document).on('click', "#erase", function () {
bErasing = true;
});
I have problem, I can just draw in first canvas, I can't draw in second, third... canvas?
Can you help me?
App = {};
$(function() {
setDrawCanvas(0);
$(document).on('click', '#nav_steps li', function() {
var $active = $(this).attr('data-n');
var $canvas = $('#canvas_panel');
$active -= 1;
setDrawCanvas($active);
$('#nav_steps li.active').removeClass('active');
$(this).addClass('active');
$canvas.find("canvas").attr("style","display: none;");
$canvas.find("canvas:eq("+ $active +")").attr("style","display: inline;");
});
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function fitToContainer(canv){
canv.width = $('#canvas_panel').width();
canv.height = $('#canvas_panel').height();
}
function setDrawCanvas(i) {
$(document).on('DOMNodeInserted', 'canvas:eq('+ i +')', function(e) {
var canvas = $(this)[0];
fitToContainer(canvas);
App.ctx = canvas.getContext("2d");
$(document).on('drag dragstart dragend', 'canvas:eq('+ i +')',function(e) {
var mousePos = getMousePos($(this)[0], e);
data = {
x: (mousePos.x),
y: (mousePos.y),
type: e.handleObj.type
}
App.draw(data);
});
});
}
// Draw Function
App.draw = function(data) {
App.ctx.strokeStyle = color;
//App.ctx.globalCompositeOperation = "destination-out";//but tay //source-over=default
App.ctx.lineWidth = linewidth;
if (data.type == "dragstart") {
App.ctx.beginPath();
App.ctx.moveTo(data.x,data.y);
} else if (data.type == "drag") {
App.ctx.lineTo(data.x,data.y);
App.ctx.stroke();
} else {
App.ctx.stroke();
App.ctx.closePath();
}
}
when I click li, console.log is OK, but I can't draw at canvas 2 ,3 ,4 ,5... I just can draw at canvas 1.
Thank
I'm going to get Url Data of selected image and put it into a created image object. I have the Url Data but this imgOrg.src = imgSrc; is not working on FireFox. any Idea why?
window.onload = function() {
var reader, imgSrc, imgOrg;
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
imgSrc = e.target.result;
console.info(imgSrc);
};
}
var avatarInput = document.querySelector('#imageFile');
avatarInput.addEventListener('change', function(e) {
console.info(imgOrg);
imgOrg = {};
var element = e.target;
imgSrc = '';
if (element.value !== '') {
reader.readAsDataURL(e.target.files[0]);
setTimeout(function() {
imgOrg = new Image();
imgOrg.src = imgSrc;
console.log("imgOrg.src= " +
imgOrg.src);
console.log(imgSrc);
console.log(imgOrg.width);
console.log(imgOrg.height);
var ratio = imgOrg.width / imgOrg.height;
var fWidth, fHeight;
if (ratio >= 1) {
fWidth = 300;
fHeight = (1 / ratio) * 300;
}
}, 1000);
}
}, false);
};
<input id="imageFile" type="file">
The main issue was: I was trying to get image's width and height before its loading was finished. After creating image object, I put rest of my code into imgOrg.onload
window.onload = function() {
var reader, imgSrc, imgOrg;
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
imgSrc = e.target.result;
console.info(imgSrc);
};
}
var avatarInput = document.querySelector('#imageFile');
avatarInput.addEventListener('change', function(e) {
imgOrg = {};
var element = e.target;
imgSrc = '';
if (element.value !== '') {
reader.readAsDataURL(e.target.files[0]);
setTimeout(function() {
imgOrg = new Image();
imgOrg.src = imgSrc;
imgOrg.onload = function() {
console.log("imgOrg.src= " +
imgOrg.src);
console.log(imgSrc);
console.log(imgOrg.width);
console.log(imgOrg.height);
var ratio = imgOrg.width / imgOrg.height;
var fWidth, fHeight;
if (ratio >= 1) {
fWidth = 300;
fHeight = (1 / ratio) * 300;
}
}
}, 1000);
}
}, false);
};
<input id="imageFile" type="file">
Is there a way to stop users on dragging the mouse down so they only can click instead of click and drag. I want htem to be only to draw dots on the canvas or any pattern i define similar to a stamp tool.
function Sketcher( canvasID, brushImage ) {
this.renderFunction = (brushImage == null || brushImage == undefined) ? this.updateCanvasByLine : this.updateCanvasByBrush;
this.brush = brushImage;
this.touchSupported = Modernizr.touch;
this.canvasID = canvasID;
this.canvas = $("#"+canvasID);
this.context = this.canvas.get(0).getContext("2d");
this.context.strokeStyle = "#000000";
this.context.lineWidth = 3;
this.lastMousePoint = {x:0, y:0};
if (this.touchSupported) {
this.mouseDownEvent = "touchstart";
this.mouseMoveEvent = "touchmove";
this.mouseUpEvent = "touchend";
}
else {
this.mouseDownEvent = "mousedown";
this.mouseMoveEvent = "mousemove";
this.mouseUpEvent = "mouseup";
}
this.canvas.bind( this.mouseDownEvent, this.onCanvasMouseDown() );
}
Sketcher.prototype.onCanvasMouseDown = function () {
var self = this;
return function(event) {
self.mouseMoveHandler = self.onCanvasMouseMove()
self.mouseUpHandler = self.onCanvasMouseUp()
$(document).bind( self.mouseMoveEvent, self.mouseMoveHandler );
$(document).bind( self.mouseUpEvent, self.mouseUpHandler );
self.updateMousePosition( event );
self.renderFunction( event );
}
}
Sketcher.prototype.onCanvasMouseMove = function () {
var self = this;
return function(event) {
self.renderFunction( event );
event.preventDefault();
return false;
}
}
Sketcher.prototype.onCanvasMouseUp = function (event) {
var self = this;
return function(event) {
$(document).unbind( self.mouseMoveEvent, self.mouseMoveHandler );
$(document).unbind( self.mouseUpEvent, self.mouseUpHandler );
self.mouseMoveHandler = null;
self.mouseUpHandler = null;
}
}
Sketcher.prototype.updateMousePosition = function (event) {
var target;
if (this.touchSupported) {
target = event.originalEvent.touches[0]
}
else {
target = event;
}
var offset = this.canvas.offset();
this.lastMousePoint.x = target.pageX - offset.left;
this.lastMousePoint.y = target.pageY - offset.top;
}
Sketcher.prototype.updateCanvasByLine = function (event) {
this.context.beginPath();
this.context.moveTo( this.lastMousePoint.x, this.lastMousePoint.y );
this.updateMousePosition( event );
this.context.lineTo( this.lastMousePoint.x, this.lastMousePoint.y );
this.context.stroke();
}
Sketcher.prototype.updateCanvasByBrush = function (event) {
var halfBrushW = this.brush.width/2;
var halfBrushH = this.brush.height/2;
var start = { x:this.lastMousePoint.x, y: this.lastMousePoint.y };
this.updateMousePosition( event );
var end = { x:this.lastMousePoint.x, y: this.lastMousePoint.y };
var distance = parseInt( Trig.distanceBetween2Points( start, end ) );
var angle = Trig.angleBetween2Points( start, end );
var x,y;
for ( var z=0; (z<=distance || z==0); z++ )
{
x = start.x + (Math.sin(angle) * z) - halfBrushW;
y = start.y + (Math.cos(angle) * z) - halfBrushH;
//console.log( x, y, angle, z );
this.context.drawImage(this.brush, x, y);
}
}
Sketcher.prototype.toString = function () {
var dataString = this.canvas.get(0).toDataURL("image/png");
var index = dataString.indexOf( "," )+1;
dataString = dataString.substring( index );
return dataString;
}
Sketcher.prototype.toDataURL = function () {
var dataString = this.canvas.get(0).toDataURL("image/png");
return dataString;
}
Sketcher.prototype.clear = function () {
var c = this.canvas[0];
this.context.clearRect( 0, 0, c.width, c.height );
}
You can achieve this by simply ignoring the mousemove and mouseup event handlers by either not initializing them or using flags to indicate that you are in stamp mode.
All you need is:
canvas.onmousedown = function(e) {
var pos = getMousePos(e);
render(pos.x, pos.y);
}
That's it, and it works similar for touch events.
To use flag (I would not recommend adding and removing handlers all the time):
var isStampMode = true;
canvas.onmousemove = function(e) {
if (isStampMode) return;
...
}
and similar for mouse up (but not really necessary unless it depends on what you do in mousedown).
Live example here
Hope this helps!
i am trying to make something like paint , in my code user chooses color for drawing , now if the user selects Fill button , the code should fill the whole screen with color user chose in the first case i-e if color was black for stroke style than canvas should be completely black,
in my code , i am getting the correct color , but cant seem to fill the canvas , with it . canvas seems to get to refresh or (stroke style='#fffff' i think)
where is my code
(my complete code now)
my html file
<li>Clear the canvas: <button id="clearCanvasSimple" type="button">Clear</button></li>
<li><span class="highlight">Choose a color: </span>
<button id="choosePurpleSimpleColors" type="button">Purple</button>
<button id="chooseGreenSimpleColors" type="button">Green</button>
<button id="chooseYellowSimpleColors" type="button">Yellow</button>
<button id="chooseBrownSimpleColors" type="button">Brown</button>
</li>
<li>Erase : <button id="chooseEraseSimpleColors" type="button">Erase</button></li>
<li>Fill with colour:<button id="chooseFillSimpleColors" type="button">Fill</button></li>
</ul>
<script type="text/javascript" src="test2.js"></script>
<script>
initGame(null, document.getElementById('movecount'));
</script>
</body>
now test.js
if(window.addEventListener) {
window.addEventListener('load', function ()
{
var canvas;
var context;
var canvasHeight = 500;
var canvasWidth = 1250;
var canvas_simple;
var context_simple;
var tool;
var paint_simpleColors;
// Initialization sequence.
function init ()
{
// Find the canvas element.
var canvasDiv = document.getElementById('canvas');
canvas_simple = document.createElement('canvas');
canvas_simple.setAttribute('height', canvasHeight);
canvas_simple.setAttribute('width', canvasWidth);
canvas_simple.setAttribute('id', 'canvasSimple');
canvasDiv.appendChild(canvas_simple);
if(typeof G_vmlCanvasManager != 'undefined')
{
canvas_simple = G_vmlCanvasManager.initElement(canvas_simple);
}
context_simple = canvas_simple.getContext("2d");
tool = new tool_pencil();
//canvas_simple.addEventListener('mousemove', ev_canvas, false);
canvas_simple.addEventListener('mousedown', ev_canvas, false);
canvas_simple.addEventListener('mousemove', ev_canvas, false);
canvas_simple.addEventListener('mouseup', ev_canvas, false);
clearCanvasSimple.addEventListener('mousedown', function () {OnButtonDown (clearCanvasSimple)}, false);
choosePurpleSimpleColors.addEventListener('mousedown', function () {ButtonDown1 (choosePurpleSimpleColors)}, false);
chooseGreenSimpleColors.addEventListener('mousedown', function () {ButtonDown2 (chooseGreenSimpleColors)}, false);
chooseYellowSimpleColors.addEventListener('mousedown', function () {ButtonDown3 (chooseYellowSimpleColors)}, false);
chooseBrownSimpleColors.addEventListener('mousedown', function () {ButtonDown4 (chooseBrownSimpleColors)}, false);
chooseEraseSimpleColors.addEventListener('mousedown', function () {ButtonDown5 (chooseEraseSimpleColors)}, false);
chooseFillSimpleColors.addEventListener('mousedown', function () {ButtonDown6 (chooseFillSimpleColors)}, false);
// canvas_simple.addEventListener('mousemove', ev_mousemove, false);
}
function tool_pencil () {
var tool = this;
this.started = false;
// This is called when you start holding down the mouse button.
// This starts the pencil drawing.
this.mousedown = function (ev) {
context_simple.beginPath();
paint_simpleColors = true;
var radius = 5;
context_simple.lineJoin = "round";
context_simple.lineWidth = radius;
context_simple.moveTo(ev._x, ev._y);
tool.started = true;
};
this.mousemove = function (ev) {
if (tool.started&&paint_simpleColors) {
context_simple.lineTo(ev._x, ev._y);
context_simple.stroke();
}
};
this.mouseup = function (ev) {
if (tool.started) {
paint_simpleColors = false;
tool.mousemove(ev);
tool.started = false;
}
};
}
function ev_canvas (ev) {
if (ev.layerX || ev.layerX == 0) { // Firefox
ev._x = ev.layerX;
ev._y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
ev._x = ev.offsetX;
ev._y = ev.offsetY;
}
// Call the event handler of the tool.
var func = tool[ev.type];
if (func) {
func(ev);
}
}
function ButtonDown1 (choosePurpleSimpleColors)
{
context_simple.strokeStyle = "#2E0854";
}
function ButtonDown2 (chooseGreenSimpleColors)
{
context_simple.strokeStyle = "#1DA237";
}
function ButtonDown3 (chooseYellowSimpleColors)
{
context_simple.strokeStyle = "#FFFF00";
}
function ButtonDown4 (chooseBrownSimpleColors)
{
context_simple.strokeStyle = "#A52A2A";
}
function ButtonDown5 (chooseEraseSimpleColors)
{
context_simple.strokeStyle = "#FFFFFF";
}
function ButtonDown6 (chooseFillSimpleColors)
{
context_simple.fillStyle = context_simple.strokeStyle;
context_simple.fillRect(0, 0, canvas.width, canvas.height);
canvas_simple.width = canvas_simple.width;
}
function OnButtonDown (clearCanvasSimple) {
context_simple.fillStyle = '#ffffff'; // Work around for Chrome
context_simple.fillRect(0, 0, canvasWidth, canvasHeight);
canvas_simple.width = canvas_simple.width; // clears the canvas
}
init();
}, false); }
i hope does helps