How to draw polygons on an HTML5 canvas? - javascript

I need to know how to draw polygons on a canvas. Without using jQuery or anything like that.

Create a path with moveTo and lineTo (live demo):
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100,50);
ctx.lineTo(50, 100);
ctx.lineTo(0, 90);
ctx.closePath();
ctx.fill();

from http://www.scienceprimer.com/drawing-regular-polygons-javascript-canvas:
The following code will draw a hexagon. Change the number of sides to create different regular polygons.
var ctx = document.getElementById('hexagon').getContext('2d');
// hexagon
var numberOfSides = 6,
size = 20,
Xcenter = 25,
Ycenter = 25;
ctx.beginPath();
ctx.moveTo (Xcenter + size * Math.cos(0), Ycenter + size * Math.sin(0));
for (var i = 1; i <= numberOfSides;i += 1) {
ctx.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides), Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides));
}
ctx.strokeStyle = "#000000";
ctx.lineWidth = 1;
ctx.stroke();
#hexagon { border: thin dashed red; }
<canvas id="hexagon"></canvas>

//poly [x,y, x,y, x,y.....];
var poly=[ 5,5, 100,50, 50,100, 10,90 ];
var canvas=document.getElementById("canvas")
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.moveTo(poly[0], poly[1]);
for(let item=2 ; item < poly.length-1 ; item+=2 ){ctx.lineTo( poly[item] , poly[item+1] )}
ctx.closePath();
ctx.fill();

//create and fill polygon
CanvasRenderingContext2D.prototype.fillPolygon = function (pointsArray, fillColor, strokeColor) {
if (pointsArray.length <= 0) return;
this.moveTo(pointsArray[0][0], pointsArray[0][1]);
for (var i = 0; i < pointsArray.length; i++) {
this.lineTo(pointsArray[i][0], pointsArray[i][1]);
}
if (strokeColor != null && strokeColor != undefined)
this.strokeStyle = strokeColor;
if (fillColor != null && fillColor != undefined) {
this.fillStyle = fillColor;
this.fill();
}
}
//And you can use this method as
var polygonPoints = [[10,100],[20,75],[50,100],[100,100],[10,100]];
context.fillPolygon(polygonPoints, '#F00','#000');

Here is a function that even supports clockwise/anticlockwise drawing do that you control fills with the non-zero winding rule.
Here is a full article on how it works and more.
// Defines a path for any regular polygon with the specified number of sides and radius,
// centered on the provide x and y coordinates.
// optional parameters: startAngle and anticlockwise
function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) {
if (sides < 3) return;
var a = (Math.PI * 2)/sides;
a = anticlockwise?-a:a;
ctx.save();
ctx.translate(x,y);
ctx.rotate(startAngle);
ctx.moveTo(radius,0);
for (var i = 1; i < sides; i++) {
ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
}
ctx.closePath();
ctx.restore();
}
// Example using the function.
// Define a path in the shape of a pentagon and then fill and stroke it.
context.beginPath();
polygon(context,125,125,100,5,-Math.PI/2);
context.fillStyle="rgba(227,11,93,0.75)";
context.fill();
context.stroke();

In addition to #canvastag, use a while loop with shift I think is more concise:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var poly = [5, 5, 100, 50, 50, 100, 10, 90];
// copy array
var shape = poly.slice(0);
ctx.fillStyle = '#f00'
ctx.beginPath();
ctx.moveTo(shape.shift(), shape.shift());
while(shape.length) {
ctx.lineTo(shape.shift(), shape.shift());
}
ctx.closePath();
ctx.fill();

You can use the lineTo() method same as:
var objctx = canvas.getContext('2d');
objctx.beginPath();
objctx.moveTo(75, 50);
objctx.lineTo(175, 50);
objctx.lineTo(200, 75);
objctx.lineTo(175, 100);
objctx.lineTo(75, 100);
objctx.lineTo(50, 75);
objctx.closePath();
objctx.fillStyle = "rgb(200,0,0)";
objctx.fill();
if you not want to fill the polygon use the stroke() method in the place of fill()
You can also check the following: http://www.authorcode.com/draw-and-fill-a-polygon-and-triangle-in-html5/
thanks

For the people looking for regular polygons:
function regPolyPath(r,p,ctx){ //Radius, #points, context
//Azurethi was here!
ctx.moveTo(r,0);
for(i=0; i<p+1; i++){
ctx.rotate(2*Math.PI/p);
ctx.lineTo(r,0);
}
ctx.rotate(-2*Math.PI/p);
}
Use:
//Get canvas Context
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.translate(60,60); //Moves the origin to what is currently 60,60
//ctx.rotate(Rotation); //Use this if you want the whole polygon rotated
regPolyPath(40,6,ctx); //Hexagon with radius 40
//ctx.rotate(-Rotation); //remember to 'un-rotate' (or save and restore)
ctx.stroke();

To make a simple hexagon without the need for a loop, Just use the beginPath() function. Make sure your canvas.getContext('2d') is the equal to ctx if not it will not work.
I also like to add a variable called times that I can use to scale the object if I need to.This what I don't need to change each number.
// Times Variable
var times = 1;
// Create a shape
ctx.beginPath();
ctx.moveTo(99*times, 0*times);
ctx.lineTo(99*times, 0*times);
ctx.lineTo(198*times, 50*times);
ctx.lineTo(198*times, 148*times);
ctx.lineTo(99*times, 198*times);
ctx.lineTo(99*times, 198*times);
ctx.lineTo(1*times, 148*times);
ctx.lineTo(1*times,57*times);
ctx.closePath();
ctx.clip();
ctx.stroke();

Let's do that with HTML and get that down to this:
<!DOCTYPE html>
<html>
<head>
<title> SVG hexagon </title>
</head>
<body>
<svg width="300" height="110" >
<polygon point="50 3, 100 28, 100 75, 50 100, 3 75, 3 25" stroke="red" fill="lime" stroke-width="5"/>
</svg>
</body>
</html>

var ctx = document.getElementById('hexagon').getContext('2d');
// hexagon
var numberOfSides = 4,
size = 25,
Xcenter = 40,
Ycenter = 40;
ctx.beginPath();
ctx.moveTo (Xcenter + size * Math.cos(0), Ycenter + size * Math.sin(0));
for (var i = 1; i <= numberOfSides;i += 1) {
ctx.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides), Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides));
}
ctx.strokeStyle = "#000000";
ctx.lineWidth = 1;
ctx.stroke();
#hexagon { border: thin dashed red; }
<canvas id="hexagon"></canvas>

Related

create dynamic line with circles in each end and parameters for width height and rotation for the line - javascript

i need help to create a function to create x quant of lines with circles in each end of the line using parameters to define the angle of rotation, width,height and color of the line and fill the space between the lines, the propours of this is making a kind of rotation max and min angle of the human arm and shoulder.
this is a image of ilustrative example what i need to do, the image of the person model is fine in png i need just to create dynamic lines.
this is the code i have so far:
function drawLine(deg,width,height,canvasId,color){
const canvas = document.getElementById(canvasId);
const ctx = canvas.getContext('2d');
ctx.rotate(deg);
ctx.fillStyle = color;
ctx.fillRect(0, 0, width, height);
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
drawLine(0,200,3,'canvas','red')
drawLine(120,200,3,'canvas1','blue')
canvas{
position: absolute;
}
<canvas id="canvas"></canvas>
<canvas id="canvas1"></canvas>
thanks very much
Based on the picture I will assume 180deg is the reference point of 0. Anything out from there is where we start counting degrees. If that is the case you will want to run a function that calculates the angle between a solid line at 180deg and two other lines from that point.
In total you will need four points. You starting point for all references (pointB in this example), another point (pointD) will be used to set the angle reference to 0 degrees. We will measure the next two angles from this line.
PointA and PointC can be adjusted as needed and we then calculate the angle from pointD/pointB vector. We can use Math.atan2 to calculate the angles of BA and BC move away from BD.
let angle1 = Math.atan2(distBC_x * distBD_y - distBC_y * distBD_x, distBC_x * distBD_x + distBC_y * distBD_y);
In this snippet I changed the color of the lines to make it easier to see what is what. You also won't need to draw the pink line. This is static so you will need to create limits and a dynamic method to change the angles.
Change the x value of pointA and pointC to change the Min and Max. Keep in mind I have to restrictions set for you to be able to switch them.
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 500;
canvas.height = 500;
//change pointA and pointC x value.
//pointA sould be your Min
//PointC should be your Max
let pointA = {x: 200, y: 250};
let pointB = {x: 250, y: 100}; //common point
let pointC = {x: 120, y: 250};
//only used to set reference to 0 at 180 degrees
let pointD = {x: pointB.x, y: pointB.y + 150};
//creating our vectors length
let distBA_x = pointB.x - pointA.x;
let distBA_y = pointB.y - pointA.y;
let distBC_x = pointB.x - pointC.x;
let distBC_y = pointB.y - pointC.y;
let distBD_x = pointB.x - pointD.x;
let distBD_y = pointB.y - pointD.y;
//calculate angle between pink and purple
let angle1 = Math.atan2(distBC_x * distBD_y - distBC_y * distBD_x, distBC_x * distBD_x + distBC_y * distBD_y);
if(angle1 < 0) {angle1 = angle1 * -1;}
let degree_angle1 = angle1 * (180 / Math.PI);
//calculate angle between purple and red
let angle2 = Math.atan2(distBA_x * distBD_y - distBA_y * distBD_x, distBA_x * distBD_x + distBA_y * distBD_y);
if(angle2 < 0) {angle2 = angle2 * -1;}
let degree_angle2 = angle2 * (180 / Math.PI);
function draw() {
ctx.textStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText('Max = '+ degree_angle1, 100, 20);
ctx.fillText('Min = '+ degree_angle2, 100, 50);
//Lines
ctx.strokeStyle = 'purple';
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(pointA.x, pointA.y);
ctx.lineTo(pointB.x, pointB.y);
ctx.stroke();
ctx.strokeStyle = 'red';
ctx.beginPath();
ctx.moveTo(pointB.x, pointB.y);
ctx.lineTo(pointC.x, pointC.y);
ctx.stroke();
ctx.strokeStyle = 'pink';
ctx.beginPath();
ctx.moveTo(pointB.x, pointB.y);
ctx.lineTo(pointD.x, pointD.y);
ctx.stroke();
//Points
ctx.fillStyle = 'purple';
ctx.beginPath();
ctx.arc(pointB.x, pointB.y, 5, 0, Math.PI*2);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.arc(pointA.x, pointA.y, 5, 0, Math.PI*2);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.arc(pointC.x, pointC.y, 5, 0, Math.PI*2);
ctx.fill();
ctx.closePath();
//Fill
ctx.fillStyle = 'rgba(113, 0, 158, 0.3)'
ctx.beginPath();
ctx.moveTo(pointA.x, pointA.y);
ctx.lineTo(pointB.x, pointB.y);
ctx.lineTo(pointC.x, pointC.y);
ctx.fill();
ctx.closePath();
}
draw()
<canvas id='canvas'></canvas>

How to get coordinates of every circle from this Canvas

I need to create a pattern where 5 circles connected by lines to a middle main circle.
So I have created dynamically by rotating in some certain angle. Now I need each and every circle's x and y axis coordinates for capturing the click events on every circle.
Please help me how to find out of coordinates of every circle?
var canvas, ctx;
function createCanvasPainting() {
canvas = document.getElementById('myCanvas');
if (!canvas || !canvas.getContext) {
return false;
}
canvas.width = 600;
canvas.height = 600;
ctx = canvas.getContext('2d');
ctx.strokeStyle = '#B8D9FE';
ctx.fillStyle = '#B8D9FE';
ctx.translate(300, 250);
ctx.arc(0, 0, 50, 0, Math.PI * 2); //center circle
ctx.stroke();
ctx.fill();
drawChildCircles(5);
fillTextMultiLine('Test Data', 0, 0);
drawTextInsideCircles(5);
}
function drawTextInsideCircles(n) {
let ang_unit = Math.PI * 2 / n;
ctx.save();
for (var i = 0; i < n; i++) {
ctx.rotate(ang_unit);
//ctx.moveTo(0,0);
fillTextMultiLine('Test Data', 200, 0);
ctx.strokeStyle = '#B8D9FE';
ctx.fillStyle = '#B8D9FE';
}
ctx.restore();
}
function drawChildCircles(n) {
let ang_unit = Math.PI * 2 / n;
ctx.save();
for (var i = 0; i < n; ++i) {
ctx.rotate(ang_unit);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(100,0);
ctx.arc(200, 0, 40, 0, Math.PI * 2);
let newW = ctx.fill();
ctx.stroke();
}
ctx.restore();
}
function fillTextMultiLine(text, x, y) {
ctx.font = 'bold 13pt Calibri';
ctx.textAlign = 'center';
ctx.fillStyle = "#FFFFFF";
// Defining the `textBaseline`…
ctx.textBaseline = "middle";
var lineHeight = ctx.measureText("M").width * 1.2;
var lines = text.split("\n");
for (var i = 0; i < lines.length; ++i) {
// console.log(lines);
if (lines.length > 1) {
if (i == 0) {
y -= lineHeight;
} else {
y += lineHeight;
}
}
ctx.fillText(lines[i], x, y);
}
}
createCanvasPainting();
<canvas id="myCanvas"></canvas>
The problem here is that you are rotating the canvas matrix and your circles are not aware of their absolute positions.
Why don't you use some simple trigonometry to determine the center of your circle and the ending of the connecting lines ?
function lineToAngle(ctx, x1, y1, length, angle) {
angle *= Math.PI / 180;
var x2 = x1 + length * Math.cos(angle),
y2 = y1 + length * Math.sin(angle);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
return {x: x2, y: y2};
}
Ref: Finding coordinates after canvas Rotation
After that, given the xy center of your circles, calculating if a coord is inside a circle, you can apply the following formula:
Math.sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)) < r
Ref: Detect if user clicks inside a circle

Simplest way to plot points randomly inside a circle

I have a basic JSFiddle whereby I want to have random points plotted inside a circle.
But I do not know how to limit the points to be inside the circle.
This is what I currently have:
var ctx = canvas.getContext('2d'),
count = 1000, // number of random points
cx = 150,
cy = 150,
radius = 148;
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(canvas.width/2, canvas.height/2, radius, 0, 2*Math.PI);
ctx.closePath();
ctx.fillStyle = '#00000';
ctx.fill();
// create random points
ctx.fillStyle = '#ffffff';
while(count) {
// randomise x:y
ctx.fillRect(x + canvas.width/2, y + canvas.height/2, 2, 2);
count--;
}
How would i go about generating random (x,y) coordinates to plot random points inside the circle?
My current fiddle: http://jsfiddle.net/e8jqdxp3/
To plot points randomly in a circle, you can pick a random value from the radius squared, then square root it, pick a random angle, and convert the polar coordinate to rectangular. The square / square root step ensures that we get a uniform distribution (otherwise most points would be near the center of the circle).
So the formula to plot a random point in the circle is the following, where r' is a random value between 0 and r2, and θ is a random value between 0 and 2π:
Screenshot of result:
Live Demo:
var canvas = document.getElementById("thecanvas");
var ctx = canvas.getContext('2d'),
count = 1000, // number of random points
cx = 150,
cy = 150,
radius = 148;
ctx.fillStyle = '#CCCCCC';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#000000';
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(canvas.width / 2, canvas.height / 2, radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
// create random points
ctx.fillStyle = '#ffffff';
while (count) {
var pt_angle = Math.random() * 2 * Math.PI;
var pt_radius_sq = Math.random() * radius * radius;
var pt_x = Math.sqrt(pt_radius_sq) * Math.cos(pt_angle);
var pt_y = Math.sqrt(pt_radius_sq) * Math.sin(pt_angle);
ctx.fillRect(pt_x + canvas.width / 2, pt_y + canvas.width / 2, 2, 2);
count--;
}
<canvas id="thecanvas" width="400" height="400"></canvas>
JSFiddle Version: https://jsfiddle.net/qc735bqw/
Randomly pick dSquared (0..radius^2) and theta (0..2pi), then
x = sqrt(dSquared) cos(theta)
y = sqrt(dSquared) sin(theta)
JSFiddle
var ctx = canvas.getContext('2d'),
count = 1000, // number of random points
cx = canvas.width/2,
cy = canvas.height/2,
radius = 148;
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(0+canvas.width/2, 0+canvas.height/2, radius, 0, 2*Math.PI);
ctx.closePath();
ctx.fillStyle = '#00000';
ctx.fill();
ctx.fillStyle = '#ffffff';
while(count) {
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;
var xDiff = cx - x;
var yDiff = cy - y;
if(Math.sqrt(xDiff*xDiff+yDiff*yDiff)<radius)
{
ctx.fillRect(x, y, 2, 2);
count--;
}
}
This worked for me:
const getRandomCoordinateInCircle = radius => {
var angle = Math.random() * Math.PI * 2;
const x = Math.cos(angle) * radius * Math.random();
const y = Math.sin(angle) * radius * Math.random();
return { x, y };
};
console.log(getRandomCoordinateInCircle(1000);
// { x: 118.35662725763385, y: -52.60516556856313 }
Returns a random point with { x: 0, y: 0} as the centre of the circle.

HTML 5 Canvas, rotate everything

I made a cylinder gauge, very similar to this one:
It is drawn using about 7 or so functions... mine is a little different. It is very fleixble in that I can set the colors, transparency, height, width, whether there is % text shown and a host of other options. But now I have a need for the same thing, but all rotated 90 deg so that I can set the height long and the width low to generate something more like this:
I found ctx.rotate, but no mater where it goes all the shapes fall apart.. ctx.save/restore appears to do nothing, I tried putting that in each shape drawing function. I tried modifying, for example, the drawOval function so that it would first rotate the canvas if horizontal was set to one; but it appeared to rotate it every single iteration, even with save/restore... so the top cylinder would rotate and the bottom would rotate twice or something. Very tough to tell what is really happening. What am I doing wrong? I don't want to duplicate all this code and spend hours customizing it, just to produce something I already have but turned horizontal. Erg! Help.
Option 1
To rotate everything just apply a transform to the element itself:
canvas.style.transform = "rotate(90deg)"; // or -90 depending on need
canvas.style.webkitTransform = "rotate(90deg)";
Option 2
Rotate context before drawing anything and before using any save(). Unlike the CSS version you will first need to translate to center, then rotate, and finally translate back.
You will need to make sure width and height of canvas is swapped before this is performed.
ctx.translate(ctx.canvas.width * 0.5, ctx.canvas.height * 0.5); // center
ctx.rotate(Math.PI * 0.5); // 90°
ctx.translate(-ctx.canvas.width * 0.5, -ctx.canvas.height * 0.5);
And of course, as an option 3, you can recalculate all your values to go along the other axis.
Look at the rotate function in this example. You want to do a translation to the point you want to rotate around.
example1();
example2();
function rotate(ctx, degrees, x, y, fn) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(degrees * (Math.PI / 180));
fn();
ctx.restore();
}
function rad(deg) {
return deg * (Math.PI / 180);
}
function example2() {
var can = document.getElementById("can2");
var ctx = can.getContext('2d');
var w = can.width;
var h = can.height;
function drawBattery() {
var percent = 60;
ctx.beginPath();
ctx.arc(35,50, 25,0,rad(360));
ctx.moveTo(35+percent+25,50);
ctx.arc(35+percent,50,25,0,rad(360));
ctx.stroke();
ctx.beginPath();
ctx.fillStyle = "rgba(0,255,0,.5)";
ctx.arc(35,50,25,0,rad(360));
ctx.arc(35+percent,50,25,0,rad(360));
ctx.rect(35,25,percent,50);
ctx.fill();
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle = "#666666";
ctx.moveTo(135,25);
ctx.arc(135,50,25, rad(270), rad(269.9999));
//ctx.moveTo(35,75);
ctx.arc(35,50,25,rad(270),rad(90), true);
ctx.lineTo(135,75);
ctx.stroke();
}
drawBattery();
can = document.getElementById("can3");
ctx = can.getContext('2d');
w = can.width;
h = can.height;
rotate(ctx, -90, 0, h, drawBattery);
}
function example1() {
var can = document.getElementById('can');
var ctx = can.getContext('2d');
var color1 = "#FFFFFF";
var color2 = "#FFFF00";
var color3 = "rgba(0,155,255,.5)"
var text = 0;
function fillBox() {
ctx.save();
ctx.fillStyle = color3;
ctx.fillRect(0, 0, can.width / 2, can.height);
ctx.restore();
}
function drawBox() {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = ctx.fillStyle = color1;
ctx.rect(10, 10, 50, 180);
ctx.font = "30px Arial";
ctx.fillText(text, 25, 45);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = color2;
ctx.lineWidth = 10;
ctx.moveTo(10, 10);
ctx.lineTo(60, 10);
ctx.stroke();
ctx.restore();
}
fillBox();
rotate(ctx, 90, can.width, 0, fillBox);
text = "A";
drawBox();
color1 = "#00FFFF";
color2 = "#FF00FF";
text = "B";
rotate(ctx, 90, can.width, 0, drawBox);
centerRotatedBox()
function centerRotatedBox() {
ctx.translate(can.width / 2, can.height / 2);
for (var i = 0; i <= 90; i += 10) {
var radians = i * (Math.PI / 180);
ctx.save();
ctx.rotate(radians);
ctx.beginPath();
ctx.strokeStyle = "#333333";
ctx.rect(0, 0, 50, 50)
ctx.stroke();
ctx.restore();
}
}
}
#can,
#can2,
#can3 {
border: 1px solid #333333
}
<canvas id="can" width="200" height="200"></canvas>
<canvas id="can2" width="200" height="100"></canvas>
<canvas id="can3" width="100" height="200"></canvas>

pattern line in different scales

I'm drawing lines with a pattern i'm creating on different canvas.
I'm translating and scaling the context matrices and creating another pattern to achieve that each line will start exactly from the beginning of the pattern. (as we know that patterns are created from the beginning of the context repeatedly for all context area and not depends on the drawing)
I've managed to do so as show below for most of the cases.
Each row represents a scale. and drawing many lines on different Y values.
Each line should have red circles repeatedly along the X axis. It is working for many scales.
The problem is in scale 1.6. The 3rd row lines. As we see, the lines in this row are not well patterned as the Y value is growing, and also the start is not right.
I think it is some floating point problem.. but i can't find the problem.
var ctx = demo.getContext('2d'),
pattern,
offset = 0;
/// create main pattern
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(8, 8, 7, 0, Math.PI * 2);
ctx.fill();
runScale(1, 0);
runScale(1.5, 120);
runScale(1.6, 240);
runScale(2, 360);
runScale(3, 480);
function runScale(scale, firstPntX) {
var newCanvasSize = {
width: demo.width * scale,
height: demo.height * scale
};
demo2.width = Math.round(newCanvasSize.width);
demo2.height = Math.round(newCanvasSize.height);
var firstPnt = {
x: firstPntX
};
var offsetPnt = {
x: 0,
y: (newCanvasSize.height / 2)
};
var ctx2 = demo2.getContext('2d');
var pt = ctx2.createPattern(demo, 'repeat');
ctx = demo3.getContext('2d');
for (var i = 20; i < 1000; i += (demo2.height + 10)) {
drawLines(i);
}
function drawLines(y) {
firstPnt.y = y;
demo2.width = demo2.width;
ctx2.fillStyle = pt;
var offsets = [firstPnt.x, y - demo2.height / 2];
ctx2.translate(offsets[0], offsets[1]);
ctx2.scale(scale, scale);
ctx2.fillRect(-offsets[0] / scale, -offsets[1] / scale, demo2.width / scale, demo2.height / scale);
ctx.lineWidth = newCanvasSize.height;
pattern = ctx.createPattern(demo2, 'repeat');
ctx.beginPath();
ctx.moveTo(firstPnt.x, firstPnt.y);
ctx.lineTo(firstPnt.x + 100, firstPnt.y);
ctx.strokeStyle = 'lightgreen';
ctx.stroke();
ctx.strokeStyle = pattern;
ctx.stroke();
}
}
canvas {
border: 1px solid #000
}
<canvas id="demo" width=16 height=16></canvas>
<canvas id="demo2"></canvas>
<canvas id="demo3" width=600 height=400></canvas>
After struggling all day with this problem i finally decided to post this question here.
And now, an hour later I've found the solution by myself..
I've decided not to delete it for the sake of the forum.
The solution is simply change the offsets.
Change this line
var offsets = [firstPnt.x, y - demo2.height / 2];
to this line
var offsets = [firstPnt.x % demo2.width,firstPnt.y % demo2.height - demo2.height / 2];
var ctx = demo.getContext('2d'),
pattern,
offset = 0;
/// create main pattern
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(8, 8, 7, 0, Math.PI * 2);
ctx.fill();
runScale(1, 0);
runScale(1.5, 120);
runScale(1.6, 240);
runScale(2, 360);
runScale(3, 480);
function runScale(scale, firstPntX) {
var newCanvasSize = {
width: demo.width * scale,
height: demo.height * scale
};
demo2.width = Math.round(newCanvasSize.width);
demo2.height = Math.round(newCanvasSize.height);
var firstPnt = {
x: firstPntX
};
var offsetPnt = {
x: 0,
y: (newCanvasSize.height / 2)
};
var ctx2 = demo2.getContext('2d');
var pt = ctx2.createPattern(demo, 'repeat');
ctx = demo3.getContext('2d');
for (var i = 20; i < 1000; i += (demo2.height + 10)) {
drawLines(i);
}
function drawLines(y) {
firstPnt.y = y;
demo2.width = demo2.width;
ctx2.fillStyle = pt;
var offsets = [firstPnt.x % demo2.width, firstPnt.y % demo2.height - demo2.height / 2];
ctx2.translate(offsets[0], offsets[1]);
ctx2.scale(scale, scale);
ctx2.fillRect(-offsets[0] / scale, -offsets[1] / scale, demo2.width / scale, demo2.height / scale);
ctx.lineWidth = newCanvasSize.height;
pattern = ctx.createPattern(demo2, 'repeat');
ctx.beginPath();
ctx.moveTo(firstPnt.x, firstPnt.y);
ctx.lineTo(firstPnt.x + 100, firstPnt.y);
ctx.strokeStyle = 'lightgreen';
ctx.stroke();
ctx.strokeStyle = pattern;
ctx.stroke();
}
}
canvas {
border: 1px solid #000
}
<canvas id="demo" width=16 height=16></canvas>
<canvas id="demo2"></canvas>
<canvas id="demo3" width=600 height=400></canvas>
Thanks for reading :D

Categories

Resources