How to create animated chart (moving plot) using pure javascript? - javascript

I need to create animated chart with moving camera without using any jquery plugin. I need to write code from scratch, I can use only jquery, no plugins.
I had managed to write code that draws chart. The only problem is how to move viewport (camera) simultaneously with chart?
I understand that I need to use translate method. But I don't how to use it correctly.
Idea of chart that I need to create:
Link to codepen:
http://codepen.io/sigmaray/pen/EyKNmK
My code:
$(function() {
// Settings
CAN_WIDTH = 300;
CAN_HEIGHT = 300;
CAN_COLOR = "#ccc";
LINE_HEIGHT = 1;
INTERVAL = 50;
$DIV = $("#container");
lineX = 0;
lineY = CAN_HEIGHT / 2;
ctx = null;
randomNum = function(max, min) {
if (min == null) {
min = 0;
}
return Math.floor(Math.random() * (max - min) + min);
};
createCanvas = function() {
canvas = document.createElement('canvas');
canvas.width = CAN_WIDTH;
canvas.height = CAN_HEIGHT;
ctx = canvas.getContext('2d');
$DIV.append(canvas);
};
timerAnimation = function(callback) {
window.setTimeout(callback, INTERVAL);
};
anim = function() {
if (lineX > CAN_WIDTH) {
lineX = 0;
}
if (lineX === 0) {
ctx.fillStyle = CAN_COLOR;
ctx.fillRect(0, 0, CAN_WIDTH, CAN_HEIGHT);
}
oldLineX = lineX;
oldLineY = lineY;
lineY = randomNum(CAN_HEIGHT * (2 / 3), CAN_HEIGHT / 3);
xOffset = randomNum(10, 1);
lineX += xOffset;
ctx.beginPath();
ctx.lineWidth = LINE_HEIGHT;
ctx.moveTo(oldLineX, oldLineY);
ctx.lineTo(lineX, lineY);
ctx.stroke();
// !!! Doesn't work as expected !!!
// ctx.translate(xOffset, 0)
// ctx.save();
};
drawingCycle = function() {
anim();
timerAnimation(drawingCycle);
};
createCanvas();
drawingCycle();
});

Related

How can I reverse the direction of this square after it reaches a certain value?

I'm trying to create an idle animation where the red rectangle moves back and forth slightly in a loop. For some reason once it reaches the specified threshhold instead of proceeding to move in the opposite direction, it just stops.
What did I do wrong?
<canvas id="myCanvas" width="1500" height="500" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Spaceship structure
var shipWidth = 250;
var shipHeight = 100;
// Canvas parameters
var cWidth = canvas.width;
var cHeight = canvas.height;
// Positioning variables
var centerWidthPosition = (cWidth / 2) - (shipWidth / 2);
var centerHeightPosition = (cHeight / 2) - (shipHeight / 2);
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function drawShip(){
ctx.clearRect(0, 0, cWidth, cHeight);
ctx.fillStyle = "#FF0000";
ctx.fillRect(centerWidthPosition,centerHeightPosition,shipWidth,shipHeight);
centerWidthPosition--;
if (centerWidthPosition < 400){
++centerWidthPosition;
}
requestAnimationFrame(drawShip);
}
drawShip();
</script>
#TheAmberlamps explained why it's doing that. Here I offer you a solution to achieve what I believe you are trying to do.
Use a velocity variable that changes magnitude. X position always increases by velocity value. Velocity changes directions at screen edges.
// use a velocity variable
var xspeed = 1;
// always increase by velocity
centerWidthPosition += xspeed;
// screen edges are 0 and 400 in this example
if (centerWidthPosition > 400 || centerWidthPosition < 0){
xspeed *= -1; // change velocity direction
}
I added another condition in your if that causes the object to bounce back and forth. Remove the selection after || if you don't want it doing that.
Your function is caught in a loop; once centerWidthPosition reaches 399 your conditional makes it increment back up to 400, and then it decrements back to 399.
here is another one as a brain teaser - how would go by making this animation bounce in the loop - basically turn text into particles and then reverse back to text and reverse back to particles and back to text and so on and on and on infinitely:
var random = Math.random;
window.onresize = function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
window.onresize();
var ctx = canvas.getContext('2d');
ctx.font = 'bold 50px "somefont"';
ctx.textBaseline = 'center';
ctx.fillStyle = 'rgba(255,255,255,1)';
var _particles = [];
var particlesLength = 0;
var currentText = "SOMETEXT";
var createParticle = function createParticle(x, y) {_particles.push(new Particle(x, y));};
var checkAlpha = function checkAlpha(pixels, i) {return pixels[i * 4 + 3] > 0;};
var createParticles = function createParticles() {
var textSize = ctx.measureText(currentText);
ctx.fillText(currentText,Math.round((canvas.width / 2) - (textSize.width / 2)),Math.round(canvas.height / 2));
var imageData = ctx.getImageData(1, 1, canvas.width, canvas.height);
var pixels = imageData.data;
var dataLength = imageData.width * imageData.height;
for (var i = 0; i < dataLength; i++) {
var currentRow = Math.floor(i / imageData.width);
var currentColumn = i - Math.floor(i / imageData.height);
if (currentRow % 2 || currentColumn % 2) continue;
if (checkAlpha(pixels, i)) {
var cy = ~~(i / imageData.width);
var cx = ~~(i - (cy * imageData.width));
createParticle(cx, cy);
}}
particlesLength = _particles.length;
};
var Point = function Point(x, y) {
this.set(x, y);
};
Point.prototype = {
set: function (x, y) {
x = x || 0;
y = y || x || 0;
this._sX = x;
this._sY = y;
this.reset();
},
add: function (point) {
this.x += point.x;
this.y += point.y;
},
multiply: function (point) {
this.x *= point.x;
this.y *= point.y;
},
reset: function () {
this.x = this._sX;
this.y = this._sY;
return this;
},
};
var FRICT = new Point(0.98);//set to 0 if no flying needed
var Particle = function Particle(x, y) {
this.startPos = new Point(x, y);
this.v = new Point();
this.a = new Point();
this.reset();
};
Particle.prototype = {
reset: function () {
this.x = this.startPos.x;
this.y = this.startPos.y;
this.life = Math.round(random() * 300);
this.isActive = true;
this.v.reset();
this.a.reset();
},
tick: function () {
if (!this.isActive) return;
this.physics();
this.checkLife();
this.draw();
return this.isActive;
},
checkLife: function () {
this.life -= 1;
this.isActive = !(this.life < 1);
},
draw: function () {
ctx.fillRect(this.x, this.y, 1, 1);
},
physics: function () {
if (performance.now()<nextTime) return;
this.a.x = (random() - 0.5) * 0.8;
this.a.y = (random() - 0.5) * 0.8;
this.v.add(this.a);
this.v.multiply(FRICT);
this.x += this.v.x;
this.y += this.v.y;
this.x = Math.round(this.x * 10) / 10;
this.y = Math.round(this.y * 10) / 10;
}
};
var nextTime = performance.now()+3000;
createParticles();
function clearCanvas() {
ctx.fillStyle = 'rgba(0,0,0,1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
(function clearLoop() {
clearCanvas();
requestAnimationFrame(clearLoop);
})();
(function animLoop(time) {
ctx.fillStyle = 'rgba(255,255,255,1)';
var isAlive = true;
for (var i = 0; i < particlesLength; i++) {
if (_particles[i].tick()) isAlive = true;
}
requestAnimationFrame(animLoop);
})();
function resetParticles() {
for (var i = 0; i < particlesLength; i++) {
_particles[i].reset();
}}

Return true when user click a bug

I am making a bug smasher game, and want Boolean value(isOnCircle) to return 'true' when a user clicks the bug. However, it always returns 'false'. Although when I tested it as a circle instead of a bug image (with 'context.arc'), it returned 'true'.
*I also inserted an image into the canvas background.
bug.r=32 is the bug image's correct radius size.
var Bug = (function () {
function Bug() {
}
return Bug;
}());
var jumpInterval;
var interval = 4000;
var bug = new Bug();
var canvas = document.getElementById('canvas');
canvas.width =727
canvas.height = 483;
var context = canvas.getContext('2d');
var background = new Image();
background.src = "images/lawn.jpg";
background.onload = function () {
context.drawImage(background, 0, 0);
}
function handleClick(evt) {
console.log(evt.x + ',' + evt.y);
var x = evt.x - 50;
var y = evt.y - 100;
// (x - center_x)^2 + (y - center_y)^2 < radius^2
var isOnCircle = Math.pow(x - bug.x, 2) + Math.pow(y - bug.y, 2) < Math.pow(bug.r, 2);
console.log(isOnCircle);
if (interval > 500) {
interval -= 300;
} else {
interval = 500;
}
console.log(interval);
}
function jump() {
bug.x = ((Math.random() * 10324897) % 500) + 1;
bug.y = ((Math.random() * 10324897) % 500) + 1;
bug.r = 32;
context.clearRect(0, 0, canvas.width, canvas.height);
var background = new Image();
background.src = "images/lawn.jpg";
background.onload = function () {
context.drawImage(background, 0, 0);
}
console.log(bug.x);
console.log(bug.y);
context.beginPath();
//context.arc(bug.x, bug.y, bug.r, 0, 2 * Math.PI);
var bugImage = new Image();
bugImage.src = "images/bug.PNG";
bugImage.onload = function () {
context.drawImage(bugImage, bug.x, bug.y);
}
context.stroke();
clearInterval(jumpInterval);
jumpInterval = setInterval(jump, interval);
}
jumpInterval = setInterval(jump, interval);
canvas.addEventListener("click", handleClick);

Canvas rotation - fixed background, moving foreground

Goal
The stripes in the background remain fixed while the cones rotate about the center.
Current State
live demo:
https://codepen.io/WallyNally/pen/yamGYB
/*
The loop function is around line 79.
Uncomment it to start the animation.
*/
var c = document.getElementById('canv');
var ctx = c.getContext('2d');
var W = c.width = window.innerWidth;
var H = c.height = window.innerHeight;
var Line = function() {
this.ctx = ctx;
this.startX = 0;
this.startY = 0;
this.endX = 0;
this.endY = 0;
this.direction = 0;
this.color = 'blue';
this.draw = function() {
this.ctx.beginPath();
this.ctx.lineWidth = .1;
this.ctx.strokeStlye = this.color;
this.ctx.moveTo(this.startX, this.startY);
this.ctx.lineTo(this.endX, this.endY);
this.ctx.closePath();
this.ctx.stroke();
}
this.update = function() {
//for fun
if (this.direction == 1) {
this.ctx.translate(W/2, H/2);
this.ctx.rotate(-Math.PI/(180));
}
}//this.update()
}//Line();
objects=[];
function initLines() {
for (var i =0; i < 200; i++) {
var line = new Line();
line.direction = (i % 2);
if (line.direction == 0) {
line.startX = 0;
line.startY = -H + i * H/100;
line.endX = W + line.startX;
line.endY = H + line.startY;
}
if (line.direction == 1) {
line.startX = 0;
line.startY = H - i * H/100;
line.endX = W - line.startX;
line.endY = H - line.startY;
}
objects.push(line);
line.draw();
}
}
initLines();
function render(c) {
c.clearRect(0, 0, W, H);
for (var i = 0; i < objects.length; i++)
{
objects[i].update();
objects[i].draw();
}
}
function loop() {
render(ctx);
window.requestAnimationFrame(loop);
}
//loop();
What I have tried
The translate(W/2, H/2) should place the context at the center of the page, then this.ctx.rotate(-Math.PI/(180)) should rotate it one degree at a time. This is the part that is not working.
Using save()and restore() is the proper way to keep some parts of an animation static while others move. I placed the save and restore in different parts of the code to no avail. There are one of two types of result : Either a new entirely static image is produced, or some erratic animation happens (in the same vein of where it is now).
Here is the changed pen: http://codepen.io/samcarlinone/pen/LRwqNg
You needed a couple of changes:
var c = document.getElementById('canv');
var ctx = c.getContext('2d');
var W = c.width = window.innerWidth;
var H = c.height = window.innerHeight;
var angle = 0;
var Line = function() {
this.ctx = ctx;
this.startX = 0;
this.startY = 0;
this.endX = 0;
this.endY = 0;
this.direction = 0;
this.color = 'blue';
this.draw = function() {
this.ctx.beginPath();
this.ctx.lineWidth = .1;
this.ctx.strokeStlye = this.color;
this.ctx.moveTo(this.startX, this.startY);
this.ctx.lineTo(this.endX, this.endY);
this.ctx.closePath();
this.ctx.stroke();
}
this.update = function() {
//for fun
if (this.direction == 1) {
this.ctx.translate(W/2, H/2);
this.ctx.rotate(angle);
this.ctx.translate(-W/2, -H/2);
}
}//this.update()
}//Line();
objects=[];
function initLines() {
for (var i =0; i < 200; i++) {
var line = new Line();
line.direction = (i % 2);
if (line.direction == 0) {
line.startX = 0;
line.startY = -H + i * H/100;
line.endX = W + line.startX;
line.endY = H + line.startY;
}
if (line.direction == 1) {
line.startX = 0;
line.startY = H - i * H/100;
line.endX = W - line.startX;
line.endY = H - line.startY;
}
objects.push(line);
line.draw();
}
}
initLines();
function render(c) {
c.clearRect(0, 0, W, H);
for (var i = 0; i < objects.length; i++)
{
ctx.save();
objects[i].update();
objects[i].draw();
ctx.restore();
}
}
function loop() {
render(ctx);
window.requestAnimationFrame(loop);
angle += Math.PI/360;
}
loop();
First I added a variable to keep track of rotation and increment it in the loop
Second I save and restore for each individual line, alternatively if all lines were going to perform the same transformation you could move that code before and after the drawing loop
Third to get the desired affect I translate so the center point is in the middle of the screen, then I rotate so that the lines are rotated, then I translate back because all the lines have coordinates on the interval [0, H]. Instead of translating back before drawing another option would be to use coordinates on the interval [-(H/2), (H/2)] etc.

How to change the zoom factor to only zoom OUT on Ken Burns effect?

I am helping a friend with a website, and he is using the Ken Burns Effect with Javascript and Canvas from this site https://www.willmcgugan.com/blog/tech/post/ken-burns-effect-with-javascript-and-canvas/
for a slide-show. It works perfectly, but he would like to change the zoom effect to where all of the images zoom OUT, instead of alternating between zooming in and out.
After about a week of "scrambling" the code unsuccessfully, he posted a question about it on the site. The reply he received was (quote) "That's definitely possible, with a few tweaks of the code. Sorry, no time to give you guidance at the moment, but it shouldn't be all that difficult" (end quote).
I can't seem to figure it out either, so I'm hoping that someone here may be of help. Below is the code as posted on the willmcgugan.com website. Any help on how to change the zoom effect would be greatly appreciated.
(function($){
$.fn.kenburns = function(options) {
var $canvas = $(this);
var ctx = this[0].getContext('2d');
var start_time = null;
var width = $canvas.width();
var height = $canvas.height();
var image_paths = options.images;
var display_time = options.display_time || 7000;
var fade_time = Math.min(display_time / 2, options.fade_time || 1000);
var solid_time = display_time - (fade_time * 2);
var fade_ratio = fade_time - display_time
var frames_per_second = options.frames_per_second || 30;
var frame_time = (1 / frames_per_second) * 1000;
var zoom_level = 1 / (options.zoom || 2);
var clear_color = options.background_color || '#000000';
var images = [];
$(image_paths).each(function(i, image_path){
images.push({path:image_path,
initialized:false,
loaded:false});
});
function get_time() {
var d = new Date();
return d.getTime() - start_time;
}
function interpolate_point(x1, y1, x2, y2, i) {
// Finds a point between two other points
return {x: x1 + (x2 - x1) * i,
y: y1 + (y2 - y1) * i}
}
function interpolate_rect(r1, r2, i) {
// Blend one rect in to another
var p1 = interpolate_point(r1[0], r1[1], r2[0], r2[1], i);
var p2 = interpolate_point(r1[2], r1[3], r2[2], r2[3], i);
return [p1.x, p1.y, p2.x, p2.y];
}
function scale_rect(r, scale) {
// Scale a rect around its center
var w = r[2] - r[0];
var h = r[3] - r[1];
var cx = (r[2] + r[0]) / 2;
var cy = (r[3] + r[1]) / 2;
var scalew = w * scale;
var scaleh = h * scale;
return [cx - scalew/2,
cy - scaleh/2,
cx + scalew/2,
cy + scaleh/2];
}
function fit(src_w, src_h, dst_w, dst_h) {
// Finds the best-fit rect so that the destination can be covered
var src_a = src_w / src_h;
var dst_a = dst_w / dst_h;
var w = src_h * dst_a;
var h = src_h;
if (w > src_w)
{
var w = src_w;
var h = src_w / dst_a;
}
var x = (src_w - w) / 2;
var y = (src_h - h) / 2;
return [x, y, x+w, y+h];
}
function get_image_info(image_index, load_callback) {
// Gets information structure for a given index
// Also loads the image asynchronously, if required
var image_info = images[image_index];
if (!image_info.initialized) {
var image = new Image();
image_info.image = image;
image_info.loaded = false;
image.onload = function(){
image_info.loaded = true;
var iw = image.width;
var ih = image.height;
var r1 = fit(iw, ih, width, height);;
var r2 = scale_rect(r1, zoom_level);
var align_x = Math.floor(Math.random() * 3) - 1;
var align_y = Math.floor(Math.random() * 3) - 1;
align_x /= 2;
align_y /= 2;
var x = r2[0];
r2[0] += x * align_x;
r2[2] += x * align_x;
var y = r2[1];
r2[1] += y * align_y;
r2[3] += y * align_y;
if (image_index % 2) {
image_info.r1 = r1;
image_info.r2 = r2;
}
else {
image_info.r1 = r2;
image_info.r2 = r1;
}
if(load_callback) {
load_callback();
}
}
image_info.initialized = true;
image.src = image_info.path;
}
return image_info;
}
function render_image(image_index, anim, fade) {
// Renders a frame of the effect
if (anim > 1) {
return;
}
var image_info = get_image_info(image_index);
if (image_info.loaded) {
var r = interpolate_rect(image_info.r1, image_info.r2, anim);
var transparency = Math.min(1, fade);
if (transparency > 0) {
ctx.save();
ctx.globalAlpha = Math.min(1, transparency);
ctx.drawImage(image_info.image, r[0], r[1], r[2] - r[0], r[3] - r[1], 0, 0, width, height);
ctx.restore();
}
}
}
function clear() {
// Clear the canvas
ctx.save();
ctx.globalAlpha = 1;
ctx.fillStyle = clear_color;
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
}
function update() {
// Render the next frame
var update_time = get_time();
var top_frame = Math.floor(update_time / (display_time - fade_time));
var frame_start_time = top_frame * (display_time - fade_time);
var time_passed = update_time - frame_start_time;
function wrap_index(i) {
return (i + images.length) % images.length;
}
if (time_passed < fade_time)
{
var bottom_frame = top_frame - 1;
var bottom_frame_start_time = frame_start_time - display_time + fade_time;
var bottom_time_passed = update_time - bottom_frame_start_time;
if (update_time < fade_time) {
clear();
} else {
render_image(wrap_index(bottom_frame), bottom_time_passed / display_time, 1);
}
}
render_image(wrap_index(top_frame), time_passed / display_time, time_passed / fade_time);
if (options.post_render_callback) {
options.post_render_callback($canvas, ctx);
}
// Pre-load the next image in the sequence, so it has loaded
// by the time we get to it
var preload_image = wrap_index(top_frame + 1);
get_image_info(preload_image);
}
// Pre-load the first two images then start a timer
get_image_info(0, function(){
get_image_info(1, function(){
start_time = get_time();
setInterval(update, frame_time);
})
});
};
})( jQuery );
If you want the simplest solution, I forked and modified your Codepen here:
http://codepen.io/jjwilly16/pen/NAovkp?editors=1010
I just removed a conditional that controls whether the zoom is moving out or in.
if (image_index % 2) {
image_info.r1 = r1;
image_info.r2 = r2;
}
else {
image_info.r1 = r2;
image_info.r2 = r1;
}
Changed to:
image_info.r1 = r2;
image_info.r2 = r1;
Now it only zooms out :)

HTML Canvas - Draw multiple rectangles in a loop

'm working on a project that calculates the number of pieces out of a sheet of paper.
I want to display the results using HTML Canvas.
So far I'm able to set the sheet size via canvas size, and also the piece size with a rectangle. These are set from text boxes #a0, #a1, #c & #d.
I'm after a result that draws the rectangles inside the canvas. The following is the code I have so far but is not working ...
function drawShapes(){
var canvas = document.getElementById('mycanvas');
canvas.width = (document.piecesForm.a0.value) /3;
canvas.height = (document.piecesForm.a1.value) /3;
var pieceWidth = (document.getElementById('c').value) / 3;
var pieceHeight = (document.getElementById('d').value) / 3;
var numAcross = canvas.width / pieceWidth;
var numDown = canvas.height / pieceHeight;
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext){
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
for(i = 0; i < numAcross; i++){
ctx.lineWidth = 1;
ctx.beginPath();
ctx.strokeRect(0,0,pieceWidth,pieceHeight);
ctx.moveTo(i*pieceWidth,0);
}
}
}
This will need another loop to display number of pieces down, any help would be great
I updated your code and it works now :
http://jsfiddle.net/gamealchemist/2cKm3/5/
var sheetSetup = {
layout: {
flipped: false,
piecePerRow: 0,
piecePerLine: 0
},
sheet: {
sizeX: 0,
sizeY: 0
},
piece: {
sizeX: 0,
sizeY: 0
}
};
function getSheetSizeX() {
return parseInt(document.piecesForm.a0.value);
}
function getSheetSizeY() {
return parseInt(document.piecesForm.a1.value);
}
function getfinalSizeX() {
return parseInt(document.piecesForm.c.value);
}
function getfinalSizeY() {
return parseInt(document.piecesForm.d.value);
}
function postMessage(dst, msg) {
document.getElementById(dst).innerHTML = msg;
}
function piecesCalc() {
var error = false;
// If the value of the sheet size textboxes is empty, then show an alert
if (!getSheetSizeX() || !getSheetSizeY()) {
postMessage("message1", "Sheet Size can't be empty!");
document.piecesForm.a0.focus();
error = true;
} else {
postMessage("message1", "");
}
// If the value of the final size textboxes is empty, then show an alert
if (!getfinalSizeX() || !getfinalSizeY()) {
postMessage("message2", "Final Size can't be empty!");
document.piecesForm.c.focus();
error = true;
} else {
postMessage("message2", "");
}
if (error) {
postMessage("answer", "---");
return;
}
var total1 = Math.floor(getSheetSizeX() / getfinalSizeX()) * Math.floor(getSheetSizeY() / getfinalSizeY());
var total2 = Math.floor(getSheetSizeY() / getfinalSizeX()) * Math.floor(getSheetSizeX() / getfinalSizeY());
if (total2 <= total1) {
sheetSetup.layout.flipped = false;
sheetSetup.layout.piecePerRow = Math.floor(getSheetSizeX() / getfinalSizeX());
sheetSetup.layout.piecePerLine = Math.floor(getSheetSizeY() / getfinalSizeY());
} else {
sheetSetup.layout.flipped = true;
sheetSetup.layout.piecePerRow = Math.floor(getSheetSizeY() / getfinalSizeX());
sheetSetup.layout.piecePerLine = Math.floor(getSheetSizeX() / getfinalSizeY());
}
sheetSetup.sheet.sizeX = getSheetSizeX();
sheetSetup.sheet.sizeY = getSheetSizeY();
sheetSetup.piece.sizeX = getfinalSizeX();
sheetSetup.piece.sizeY = getfinalSizeY();
var total = Math.max(total1, total2);
postMessage("answer", total + " per sheet");
// document.piecesForm.nbpieces.value = total;
}
function drawShapes() {
console.log(sheetSetup);
var displayRatio = 5;
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
canvas.width = Math.floor( sheetSetup.sheet.sizeX / displayRatio );
canvas.height = Math.floor( sheetSetup.sheet.sizeY / displayRatio );
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
var usedWidth = sheetSetup.layout.flipped ? sheetSetup.piece.sizeY : sheetSetup.piece.sizeX;
var usedHeight = sheetSetup.layout.flipped ? sheetSetup.piece.sizeX : sheetSetup.piece.sizeY;
usedWidth /= displayRatio;
usedHeight /= displayRatio;
for (var line = 0; line < sheetSetup.layout.piecePerLine; line++) {
for (var row = 0; row < sheetSetup.layout.piecePerRow; row++) {
ctx.strokeRect(row * usedWidth, line * usedHeight, usedWidth, usedHeight);
}
}
}
}
Make
var total=0 as Global variable
The code is
for (i = 0; i < numAcross; i++) {
ctx.lineWidth = 1;
ctx.beginPath();
ctx.strokeRect(i*pieceWidth, 0, pieceWidth, pieceHeight);
ctx.moveTo(i * pieceWidth, 5);
}
for (i = 0; i < total-numAcross; i++) {
ctx.lineWidth = 1;
ctx.beginPath();
ctx.strokeRect(i*pieceWidth, pieceHeight, pieceWidth, pieceHeight);
ctx.moveTo(i * pieceWidth, 5);
}
Fiddle:
Fiddle

Categories

Resources