fill the canvas with the select colour (stroke style) html5 - javascript

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

Related

html pause canvas game works... but my resume does not. Why not?

Currently working on a canvas game. My pause functionality works but my resume does not. Ive seen other example on here with the similar problem but it's not helping. What am I doing wrong?
var paused = false;
document.onkeydown = function onKeyPause(event) {
if (event.keyCode === 80)
paused = !paused;
return;}
var gamearea = {
canvas: document.createElement("canvas"),
start: function () {
this.canvas.width = 250;
this.canvas.height = 287;
...more canvas css.........
update: function () {
gamearea.context.clearRect(0, 0, 300, 400);
document.getElementById("score").innerText = "Score: " + score;
if (score == 20) {
gamearea.stop(true);
return;
}
if (targetGone()) {
gamearea.stop(false);
return;
}
if (paused) {
gamearea.pausedGame(true);
return;
}
pausedGame: function (paused) {
gamearea.canvas.removeEventListener("click", clickHandler, event);
gamearea.context.fillRect(0, 100, 300, 100);
gamearea.context.font = "20px helvetica";
... more canvas css ..
if (paused) return; // <--- stop looping
update();
draw();
window.requestAnimationFrame(loop, canvas);
},
requestAnimationFrame returns an Id that you can use to "pause" your game loop
Use cancelAnimationFrame(RETURNED_ID)
simple example
// global variable
let loopId = null;
function start() {
...
loopId = requestAnimationFrame(loop);
}
function loop() {
...
loopId = requestAnimationFrame(loop);
}
function pauseHandler() {
if (looId) {
cancelAnimationFrame(loopId)
}
}

Wait for the user mouse down event before continuing game loop

I have a game loop that re-draws a game board after each player makes a move. I would like to pause the main loop and wait until a player places a piece on the board, i.e. triggers a mouse down event on the canvas. Right now the game loop continues to redraw the board. Is there a way to wait for the player to move before continuing the loop?
var initGameLoop = function() {
player1 = new humanPlayer();
player2 = new computerPlayer();
while (gameState) {
redraw();
player1.acceptMove();
redraw();
player2.acceptMove();
}
};
var humanPlayer = function() {
this.acceptMove = function() {
canvas.addEventListener("mousedown", addPieceWithMouse);
};
};
var computerPlayer = function() {
this.acceptMove = function() {
computerMove();
};
};
This shows the desired effect using a continuous game loop. It does not run the redraw while the gameState is playerMove.
var canvas = document.getElementById("can");
var ctx = canvas.getContext('2d');
var gameState = "normal";
var initGameLoop = function() {
player1 = new humanPlayer();
player2 = new computerPlayer();
function animate () {
if(gameState === "playerMove") {
} else {
player1.acceptMove();
player2.acceptMove();
redraw();
}
requestAnimationFrame(animate)
}
animate()
};
function redraw() {
ctx.font="10px Sans-serif";
ctx.fillStyle="#333333";
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.fillStyle="#00FFFF";
ctx.fillText(player1.count,100,50);
ctx.fillStyle="#FFFF00";
ctx.fillText(player2.count,100,70);
ctx.fillStyle="#EEEEEE";
ctx.fillText("PLAYER 1:", 40,50);
ctx.fillText("PLAYER 2:", 40,70);
}
function addPieceWithMouse() {
gameState = "playerMove";
}
function finishMove() {
gameState = "normal";
}
canvas.addEventListener("mousedown", addPieceWithMouse);
canvas.addEventListener("mouseup", finishMove);
var humanPlayer = function() {
this.count = 0;
this.acceptMove = function() {
this.count += Math.floor(Math.random()*2)
};
};
var computerPlayer = function() {
this.count = 0;
this.acceptMove = function() {
this.computerMove();
};
this.computerMove = function() {
this.count += Math.floor(Math.random()*2);
};
};
initGameLoop();
<canvas id="can"></canvas>

Preview image and canvas

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" />

mouseclick event JavaScript doesn't work in Firefox

I made this piece of code for turning sound on/off in a game I'm making.
It works great with Google Chrome and IE. Proud as I was I gave the code to my friend who tried it on Firefox..
But he made me sad by saying it didn't work on Firefox...
I don't know why it doesn't work, can somebody tell me what's wrong or maybe what I have to change?
P.S.: "geluidknop" is Dutch for "soundbutton".
var audio = new Audio('Beep.mp3');
function playAudio() {
audio.play();
}
function pauseAudio() {
audio.pause();
audio.currentTime = 0;
}
window.addEventListener('keydown', playAudio);
audio.play();
function CanvasApp() {
'use strict'
var canvas = document.getElementById("canvas"),
style = window.getComputedStyle(canvas),
context = canvas.getContext("2d"),
source1 = "geluidaan.png",
source2 = "geluiduit.png",
click = false,
geluidknop = {x: 0, y: 0, width: 1024, height: 768};
geluidknop.aspect = geluidknop.height / geluidknop.width;
geluidknop.width = 500;
geluidknop.height = geluidknop.width * geluidknop.aspect;
canvas.width = parseInt(style.width, 10);
canvas.height = parseInt(style.height, 10);
var img = new Image();
img.onload = function () {
context.drawImage (img, geluidknop.x, geluidknop.y, geluidknop.width, geluidknop.height);
};
img.src = source1;
function changeImage() {
if (click) {
img.src = source2;
} else {
img.src = source1;
}
}
function MouseClick() {
var rect = canvas.getBoundingClientRect(),
x = event.clientX - rect.left,
y = event.clientY - rect.top;
if (x >= geluidknop.x && x <= geluidknop.x + geluidknop.width) {
if (y >= geluidknop.y && y <= geluidknop.y + geluidknop.height) {
if (click) {
click = false;
playAudio();
changeImage();
}else {
click = true;
pauseAudio();
changeImage();
}
}
}
context.save();
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
context.restore();
}
canvas.addEventListener('click', MouseClick);
function restartAudio() {
audio.currentTime = 0;
audio.play();
}
audio.addEventListener('ended', restartAudio);
}
function WindowLoaded() {
'use strict';
CanvasApp();
}
window.addEventListener("load", WindowLoaded);
I think you forgot to pass event to your event handler function. Chrome will fill this in, but Firefox will not.
It should be:
function MouseClick(event) {}
This issue might not be your code, but more likley .mp3 support in firefox.
Dependant on the version of firefox he was using a .mp3 file might not be supported
check out the mozilla docs on audio support

Canvas and animation

I was trying to create a sample paint application using HTML 5 canvas. Then I added a button to redraw what user had drawn earlier. I am not sure what I am doing wrong or may be completely wrong. When I click redraw button multiple times it generates some magical animation by drawing lines all over. Even though if I log the starting point of drawing the image its same every time.
Demo: http://jsfiddle.net/BW57H/6/
Steps to reproduce:
Draw some circle or rectangle or something by clicking the mouse and dragging it on the rectangular box. Then click reset and redraw , click redraw couple of times after that and see the result.
I am not sure what I have done. I have not read a lot about Canvas. But I am curious to know what is going on here. Thanks.
html
<body>
<canvas id="paint" width="600px" height="300px"></canvas>
<div id="controls">
<button name="reset" id="reset">Reset</button>
<button name="redraw" id="redraw">Re-Draw</button>
</div>
</body>
css
#paint{
border: solid;
}
js
$(document).ready(function(){
var x, y, context, painter;
var xCounter = 0 , yCounter = 0;
var xarray = [];
var yarray = [];
function init(){
while(document.getElementById("paint") === undefined){
//do nothing
}
console.log("Loaded document now registering events for canvas");
var canvas = document.getElementById("paint");
context = canvas.getContext('2d');
painter = new Painter();
canvas.addEventListener('mousedown', capture, false);
canvas.addEventListener('mouseup', capture, false);
canvas.addEventListener('mousemove', capture, false);
document.getElementById("reset").addEventListener("click",function(){ clearCanvas(canvas);}, false);
document.getElementById("redraw").addEventListener("click", function(){
autoDraw();
}, false);
}
function clearCanvas(canvas){
context.save();
// Use the identity matrix while clearing the canvas
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
// Restore the transform
context.restore();
};
function capture(event){
if(event.which !== 1){
return;
}
x = event.layerX;
y = event.layerY;
switch(event.type){
case 'mousedown':
painter.startPaint(event);
break;
case 'mouseup':
painter.endPaint(event);
break;
case 'mousemove':
painter.paint(event);
break;
}
};
var Painter = function(){
var self = this;
self.paintStarted = false;
self.startPaint = function(event){
self.resetRecordingParams();
self.paintStarted = true;
context.beginPath();
context.moveTo(x,y);
self.record();
}
self.endPaint = function(event){
self.paintStarted = false;
self.record();
self.paint(event)
}
self.paint = function(event){
if(self.paintStarted){
context.lineTo(x,y);
context.stroke();
self.record();
}
}
self.record = function(){
xarray[xCounter++] = x;
yarray[yCounter++] = y;
}
self.resetRecordingParams = function(){
xarray = [];
yarray = [];
xCounter = 0;
yCounter= 0;
}
return self;
}
function autoDraw(){
context.beginPath();
console.log('starting at: '+xarray[0]+','+yarray[0]);
context.moveTo(xarray[0],yarray[0]);
for (var i = 0; i < xarray.length; i++) {
setTimeout(drawLineSlowly, 1000+(i*20), i);
};
}
function drawLineSlowly(i)
{
context.lineTo(xarray[i],yarray[i]);
context.stroke();
}
init();
});
You don't have any kind of check to see whether or not you are already drawing, so here is your code with those changes commented, as well as the real-pixel-location fixes (http://jsfiddle.net/upgradellc/htJXy/1/):
$(document).ready(function(){
var x, y, context, painter, canvas;
var xCounter = 0 , yCounter = 0;
var xarray = [];
var yarray = [];
function init(){
while(document.getElementById("paint") === undefined){
//do nothing
}
console.log("Loaded document now registering events for canvas");
canvas = document.getElementById("paint");
context = canvas.getContext('2d');
painter = new Painter();
canvas.addEventListener('mousedown', capture, false);
canvas.addEventListener('mouseup', capture, false);
canvas.addEventListener('mousemove', capture, false);
document.getElementById("reset").addEventListener("click",function(){ clearCanvas(canvas);}, false);
document.getElementById("redraw").addEventListener("click", function(){
autoDraw();
}, false);
}
function clearCanvas(canvas){
context.save();
// Use the identity matrix while clearing the canvas
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
// Restore the transform
context.restore();
};
function capture(event){
if(event.which !== 1){
return;
}
tempPos = getMousePos(canvas, event);
x = tempPos.x;
y = tempPos.y;
switch(event.type){
case 'mousedown':
painter.startPaint(event);
break;
case 'mouseup':
painter.endPaint(event);
break;
case 'mousemove':
painter.paint(event);
break;
}
};
var Painter = function(){
var self = this;
self.paintStarted = false;
//this keeps track of whether or not we are currently auto drawing
self.currentlyAutoDrawing = false;
self.startPaint = function(event){
self.resetRecordingParams();
self.paintStarted = true;
context.beginPath();
context.moveTo(x,y);
self.record();
}
self.endPaint = function(event){
self.paintStarted = false;
self.record();
self.paint(event);
}
self.paint = function(event){
if(self.paintStarted){
context.lineTo(x,y);
context.stroke();
self.record();
}
}
self.record = function(){
xarray[xCounter++] = x;
yarray[yCounter++] = y;
}
self.resetRecordingParams = function(){
xarray = [];
yarray = [];
xCounter = 0;
yCounter= 0;
}
return self;
}
function autoDraw(){
context.beginPath();
//If we are already auto-drawing, then we should just return instead of starting another drawing loop cycle
if(painter.currentlyAutoDrawing){
console.log("painter is already auto drawing");
return;
}
painter.currentlyAutoDrawing = true;
console.log('starting at: '+xarray[0]+','+yarray[0]);
context.moveTo(xarray[0],yarray[0]);
for (var i = 0; i < xarray.length; i++) {
setTimeout(drawLineSlowly, 1000+(i*20), i);
};
}
function drawLineSlowly(i)
{
//when we reach the last element in the array, update painter with the fact that autodrawing is now complete
if(xarray.length == i+1){
painter.currentlyAutoDrawing=false;
}
console.log(xarray.length+" "+i);
context.lineTo(xarray[i],yarray[i]);
context.stroke();
}
function getMousePos(canv, evt) {
var rect = canv.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
init();
});
Obviously you don't stop the previous timeout loop before you start a new...
Use setInterval instead of setTimeout, and clearInterval by next push. So I think the problem is not with the canvas, just with your redraw animation. Btw it is strange because there is some difference between the redraw and the original draw...
var drawInterval = null;
function autoDraw(){
if (drawInterval) {
//here your can reset the previous - still running - redraw
clearInterval(drawInterval);
}
context.beginPath();
console.log('starting at: '+xarray[0]+','+yarray[0]);
context.moveTo(xarray[0],yarray[0]);
var i=0;
setInterval(function (){
++i;
if (i<xarray.length)
drawLineSlowly(i);
else
clearInterval(drawInterval);
},20);
}
note:
There is still bug in the redraw, but at least it does not kill the browser...
Btw the strange "animation" is because you does not check by redraw if you are currently drawing or not, so you start draw and redraw together and they interfere... You have to stop redraw when you start drawing.

Categories